【问题标题】:Use Twig variable as a property name of an other Twig variable使用 Twig 变量作为其他 Twig 变量的属性名称
【发布时间】:2013-01-07 09:05:00
【问题描述】:

我必须使用 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 %}

谢谢。

【问题讨论】:

  • 你试过attribute function吗?
  • @mbosecke:这对我有用,只需将其写为答案,以便我接受,谢谢 :)

标签: php symfony twig


【解决方案1】:

attribute function 是您正在寻找的。​​p>

编辑:

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

【讨论】:

  • 答案中的链接已损坏 - 看看here
【解决方案2】:
    {% for object in objects %}
        {% for column in columns %}
            {{ attribute(object, column) }} {# equivalent to php $object[$column] #}
        {% endfor %}
    {% endfor %}

使用 Twig Attribute Function (Twig > 1.2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多