如何使用 Twig 的属性函数访问嵌套对象属性

我正在尝试使用 twig 变量来访问另一个 twig 变量的属性,该变量在我找到“属性”函数之前不起作用。除了需要访问嵌套属性的情况外,效果很好。当包含属性的变量实际上是对象 + 属性时,它不起作用。例如:


{{ attribute(object1, variable) }}其中变量 = 名称,工作正常。 {{ attribute(object1, variable) }}其中变量 = object2.name,不起作用。但是,硬编码测试{{ object1.object2.name }}确实有效。


这是我如何做到这一点......我有一个 yaml 配置文件,它由控制器解析并将其传递给名为“config”的数组中的 twig。它包含定义树枝模板显示内容的参数。


fields:

  - name: company.name

    label: 'ODM'

    indexView: true

    recodrdView: true

  - name: location

    label: 'Location'

    indexView: true

    recordView: true

此外,一组对象(实体)被传递到模板进行渲染。


上面的“fields.name”是实体属性的名称。我遍历实体数组,然后遍历 config.fields 数组以确定要显示的内容。这是树枝代码:


{% for data in datum %}

    <tr>

    {% for field in config.fields %}

        {% if field.indexView %}

            <td>{{ attribute(data, field.name }}</td>       

        {% endif %}

    {% endfor %}

    </tr>

{% endfor %}

我收到错误:


Neither the property "company.name" nor one of the methods "company.name()", "getcompany.name()"/"iscompany.name()"/"hascompany.name()" or "__call()" exist and have public access in class "App\Entity\Odm".

我想我可以用 '.' 拆分 field.name 字符串。分隔符,然后对属性进行必要数量的调用,但我真的希望有一个更有说服力的解决方案。我也试过 _context['data.' ~ field.name] - 也没有运气。


有任何想法吗?


万千封印
浏览 170回答 3
3回答

慕工程0101907

您可以使用以下代码段实现此目的:主枝{% import 'macro.twig' as macro %}{{ macro.get_attribute(foo, 'bar.foobar') }}大树枝{% macro get_attribute(object, attributes) %}    {% apply spaceless %}    {% set attributes = attributes|split('.') %}    {% set value = object %}    {% for attribute in attributes %}        {% set value = attribute(value, attribute|trim) is defined ? attribute(value, attribute|trim) : null %}    {% endfor %}    {{ value }}    {% endapply %}    {% endmacro %}演示但是,请注意,如果您尝试为此使用宏并将“输出”存储在变量中,请记住,宏将返回Twig_Markup. 这意味着您以后不能使用该值。一个例子:数据foo:    bar:        foobar: 'Lorem Lipsum'主枝{% set bar = macro.get_attribute(foo, 'bar') %}{{ bar.foobar }} {# <--- error cause `foobar` is not a member of `Twig_Markup` #}bar实际上的实际值甚至不是一个对象或数组,而只是一个字符串,在这个例子中,Array作为内容{% set bar = macro.get_attribute(foo, 'bar') %}{{ bar }} {# output: Array #}
打开App,查看更多内容
随时随地看视频慕课网APP