如何在foreach Symfony 2~twig中使用渲染变量

时间:2016-04-29 22:00:39

标签: php symfony twig

这不是我第一次遇到这个问题,我无法解决它! 实际上,我正在使用控制器渲染一个模板,该控制器为渲染页面提供了许多变量。其中之一,称为$ categories,其中有许多类别对象,其中一个是集合引用另一个类别。

关键是,我正在尝试执行此代码,但很明显我收到错误,因为即时尝试打印为字符串集合

{% for category in categories %}
    <tr>
        <td>{{ category.name }}</td>
        <td>{{ category.description }}</td>
        <td>{{ category.isPublic }}</td>
        <td>{{ category.parentCategory }}</td>
        <td>{{ category.childrens }}</td>
        <td>
            <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
            <i class="fa fa-times" aria-hidden="true"></i>
        </td>
    </tr>
{% endfor %}

所以,我决定尝试类似的事情:

{% for category in categories %}
<tr>
    <td>{{ category.name }}</td>
    <td>{{ category.description }}</td>
    <td>{{ category.isPublic }}</td>
    <td>{{ category.parentCategory }}</td>
    <td>
        {% for children in {{ category.childrens }} %}
            children.name
        {% endfor %}
    </td>
    <td>
        <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
        <i class="fa fa-times" aria-hidden="true"></i>
    </td>
</tr>

问题:

我不知道如何在foreach中使用渲染变量,我得到了这个错误:

  

哈希键必须是带引号的字符串,数字,名称或括在括号中的表达式(AppBundle中值为“{”的意外标记“标点符号”:第55行的admin:category / listCategory.html.twig 。

3 个答案:

答案 0 :(得分:4)

{{ }}{% %}{# #}是Twig的开放和关闭代码。 PHP代码中的<?php ?> Similair。一旦你使用了一个开放的标签,文本就会被Twig解析,直到找到close标签(这也是在PHP中完成的事情,唯一的区别是Twig有一个不同的标签来回显东西)。

一旦打开,您就不必再次重新打开它。你不想转储category.childrens,你想在for循环中使用它。因此,不要执行:{% for children in {{ category.childrens }} %},而是使用{% for children in category.childrens %}

(you can compare this to PHP, doing
    <?php foreach (<?php echo $category->childrens ?> as $children) { ?>
doesn't make much sense).

答案 1 :(得分:1)

错误可能来自这一行:

{% for children in {{ category.childrens }} %}

这不是有效的语法,{{ }}不能在另一个Twig标记内使用。

以下代码应该有效:

{% for children in category.childrens %}

答案 2 :(得分:0)

说实话,我有使用twig模板语言的经验,所以我可能在这里错了,但我使用其他语言的经验告诉我以下代码:

    {% for children in {{ category.childrens }} %}
        children.name
    {% endfor %}

应该是这样的:

    {% for children in category.childrens %}
        {{ children.name }}
    {% endfor %}