Skip to content

Commit bd7e899

Browse files
authored
Merge pull request #42 from wmde/feat/handle-array-type-value-substitution-20250630
Handle array-type value substitution in Vue templates
2 parents e214234 + 7b0ee2e commit bd7e899

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/Component.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,13 @@ private function stripEventHandlers( DOMNode $node ) {
8787
}
8888
}
8989

90+
private function convertDataValueToString( $value ) {
91+
if ( is_string( $value ) ) {
92+
return $value;
93+
}
94+
return json_encode( $value );
95+
}
96+
9097
/**
9198
* @param DOMNode $node
9299
* @param array $data
@@ -100,8 +107,7 @@ private function replaceMustacheVariables( DOMNode $node, array $data ) {
100107

101108
foreach ( $matches['expression'] as $index => $expression ) {
102109
$value = $this->app->evaluateExpression( $expression, $data );
103-
104-
$text = str_replace( $matches[0][$index], $value, $text );
110+
$text = str_replace( $matches[0][$index], $this->convertDataValueToString( $value ), $text );
105111
}
106112

107113
if ( $text !== $node->textContent ) {

tests/php/TemplatingTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,22 @@ public function testTemplateWithObjectValuedNonClassAttribute_ThrowsError() {
346346
);
347347
}
348348

349+
public function testMoustacheVariableWithArrayListTypeSubstitution() {
350+
$result = $this->createAndRender(
351+
'<p>{{ my.data.variable }}</p>',
352+
[ 'my' => [ 'data' => [ 'variable' => [ 1, 2, 3 ] ] ] ]
353+
);
354+
$this->assertSame( '<p>[1,2,3]</p>', $result );
355+
}
356+
357+
public function testMoustacheVariableWithArrayObjectTypeSubstitution() {
358+
$result = $this->createAndRender(
359+
'<p>{{ my.data.variable }}</p>',
360+
[ 'my' => [ 'data' => [ 'variable' => [ "a" => "b", "c" => "d" ] ] ] ]
361+
);
362+
$this->assertSame( '<p>{"a":"b","c":"d"}</p>', $result );
363+
}
364+
349365
/**
350366
* @param string $template HTML
351367
* @param array $data

0 commit comments

Comments
 (0)