在 Twig 中传递 属性 的名称?

Pass the name of a property in Twig?

在 PHP 中,我可以指定要使用的元素 / 属性 只需传递一个带有元素名称的变量,例如:

$array[$name]
$object -> $name

如何用 Twig 做到这一点?

例如,从MySQL数据库中读取一个数组行,其主键字段可以是id、ItemId、Serial、number 或任何内容,我如何传入主键的列名以便Twig 正确显示行的主键?

{{ row.id }}
{{ row.ItemId }}
{{ row.Serial }}
{{ row.number }}

但就像:

{{ row.primary }}

其中 primary 是主键的实际列名的名称,可以是 id、ItemId 或其他。

有什么方法可以做到这一点?

好像很简单,用attribute()就可以了。

通过:

array(
  'primaryKey' => 'id'
  'row' => array(
    'id' => 1,
    'title' => 'some title'
  )
)

在树枝模板中:

{{ attribute(row, primaryKey) }}

这与以下内容具有相同的效果:

{{ row.id }}