attribute
警告
attribute
函数从 Twig 3.15 版本开始已被弃用。请使用点运算符,该运算符现在接受用括号包裹的任何表达式。
请注意,此函数在 Twig 4.0 中仍然可用,以实现更平滑的升级路径。
attribute
函数允许您访问对象或数组的属性、方法或属性,当该属性、方法或属性的名称存储在变量中或通过表达式动态生成时
1 2 3 4 5 6 7 8 9 10 11
{# method_name is a variable that stores the method to call #}
{{ attribute(object, method_name) }}
{# you can also pass arguments when calling a method #}
{{ attribute(object, method_name, arguments) }}
{# the method/property name can be the result of evaluating an expression #}
{{ attribute(object, 'some_property_' ~ user.type) }}
{# in addition to objects, this function works with plain arrays as well #}
{{ attribute(array, item_name) }}
此外,defined
测试可以检查动态属性是否存在
1
{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}
注意
解析算法与 .
运算符使用的算法相同。
参数
variable
:变量attribute
:属性名称arguments
:要传递给调用的参数数组