Twig

灵活、快速且安全的
PHP 模板引擎

a Symfony Product
文档 函数 attribute
您正在阅读 Twig 3.x 的文档。切换到 Twig 1.x, 2.x 的文档。

问题与反馈

许可

Twig 文档 基于新 BSD 许可 授权。

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:要传递给调用的参数数组