如何在foreach Symfony 2~分支中使用渲染的变量



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

重点是,我试图做这段代码,但很明显我遇到了一个错误,因为我试图将一个集合打印为字符串

{% 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中使用渲染变量,我遇到了这个错误:

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

{{ }}{% %}{# #}是Twig的打开和关闭标记。在PHP代码中Similair到<?php ?>。一旦使用了open标记,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).

错误可能来自以下行:

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

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

以下代码应该有效:

{% for children in category.childrens %}

老实说,我对tridge模板语言没有任何经验,所以我可能错了,但我对其他语言的经验告诉我以下代码:

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

应该看起来像这样:

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

最新更新