I'm loading a twig template and it contains a for
loop with runs through a variable of type array and outputs ok, now I'm trying to include a snippet of html within the for loop and pass in the data from the loop and populate the sub template.
mainSet.template.php
{% for set in sets %}
{% include 'inner/set.template.php' with {'set'} only %}
{% endfor %}
inner/set.template.php
, inner is a sub-folder within the directory that mainSet.template.php
exists in.
set.template.php
<div class="set">
<span>{{ set.name }}</span>
</div>
This is the error I'm getting:
Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'A hash key must be followed by a colon (:). Unexpected token "punctuation" of value "}" ("punctuation" expected with value ":") in "index" at line 4.' in C:\htdocs\vendor\twig\twig\lib\Twig\TokenStream.php:87
Stack trace:
#0 C:\htdocs\vendor\twig\twig\lib\Twig\ExpressionParser.php(284): Twig_TokenStream->expect(9, ':', 'A hash key must...')
#1 C:\htdocs\vendor\twig\twig\lib\Twig\ExpressionParser.php(188): Twig_ExpressionParser->parseHashExpression()
#2 C:\htdocs\vendor\twig\twig\lib\Twig\ExpressionParser.php(84): Twig_ExpressionParser->parsePrimaryExpression()
#3 C:\htdocs\vendor\twig\twig\lib\Twig\ExpressionParser.php(41): Twig_ExpressionParser->getPrimary()
#4 C:\htdocs\vendor\twig\twig\lib\Twig\TokenParser\Include.php(46): Twig_ExpressionParser->parseExpression()
#5 C:\htdocs\ in C:\htdocs\vendor\twig\twig\lib\Twig\TokenStream.php on line 87
The code is to broken up over a custom framework to post it all here, the initial twig template is loaded like below and an array of set data is passed in.
$twigLoader = new Twig_Loader_Array(array(
'index' => file_get_contents((!empty($dirLevel) ? $dirLevel : '').TEMPLATE_DIR . 'index' . TEMPLATE_EXT)
));
...
$twig = new Twig_Environment($twigLoader);
$page = $twig->render('index', $indexData);
$indexData
Array
(
[sets] => Array
(
[0] => stdClass Object
(
[name] => test 1
)
[1] => stdClass Object
(
[name] => test 2
)
[2] => stdClass Object
(
[name] => test 3
)
)
)
Is it even possible to do what I'm trying, I know you can include templates in templates so maybe I have some syntax wrong!?
change {% include 'inner/set.template.php' with {'set'} only %}
to {% include 'inner/set.template.php' with {'set':set} only %}
syntax for associative arrays is {key1:value1, key2:value2, ...}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.