将Twig变量用作另一个Twig变量的属性名

26

我必须将Twig变量用作另一个Twig变量的属性。

在for循环中,我获取特定实体的属性,并希望使用这些属性来获取其他for循环中实体变量的属性内容。

以下是一些代码以使此更清晰:

{% for entity in entities  %}

{{entity.foo}}, {{entity.bar}}<br />

{% for property in specialdynamicproperties %}
{{entity.property}} <!-- property has the content foobar for example, I want to use it as the property accessor for entity -->
{% endfor %}

{% endfor %}

谢谢。


5
你尝试过使用 attribute function 吗? - mbosecke
@mbosecke:这对我有效,只需将其编写为答案,以便我可以接受它,谢谢 :) - Aykut Çevik
2个回答

40
attribute 函数是您正在寻找的内容。

编辑:

  {{ attribute(object, method) }}
  {{ attribute(object, method, arguments) }}
  {{ attribute(array, item) }}

答案中的链接已经失效 - 请查看这里 - Augustine Calvino

19
    {% for object in objects %}
        {% for column in columns %}
            {{ attribute(object, column) }} {# equivalent to php $object[$column] #}
        {% endfor %}
    {% endfor %}

使用Twig的Attribute函数(Twig > 1.2)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接