为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
万千封印 2021-06-16 18:15:52
我正在尝试使用 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] - 也没有运气。有任何想法吗?
查看完整描述

3 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

您可以使用以下代码段实现此目的:


主枝


{% 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 #}


查看完整回答
反对 回复 2021-06-19
  • 3 回答
  • 0 关注
  • 169 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号