首页 > 解决方案 > Twig 将变量解释为字符串并且不读取它们的内容

问题描述

我在树枝中有一个名为 mark 的数组,其中包含类。这是一个摘录:

array(7) {
  [0]=>
     object(stdClass)#526 (11) {
        ["Algebre"]=>
        string(2) "11"
        ["ElectroCinetics"]=>
        string(2) "16"
        ["Statistics"]=>
        string(1) "8"
        ["French"]=>
        string(1) "9"
        ["Commerce_Int"]=>
        string(2) "14"
        ["Total"]=>
        string(5) "11.23"
        ["name"]=>
        string(16) "Jonh Doe"
    }

 

现在的重点是我不知道密钥的名称,因为它们是由管理员动态添加的。我所能做的就是从数据库中获取它们并将它们存储到一个名为模块的变量中。所以我有这样的事情:

{%set module="Electrocinetics" %}

因此,当我想显示标记时,我会这样做: Mark:{{mark.module}}

并且没有显示任何内容,因为 twig 认为它应该在数组中寻找的键名为模块。但我希望它读取变量的内容。有没有办法强制 twig 读取变量的内容?

标签: arraystwig

解决方案


你可以使用attribute函数。
https://twig.symfony.com/doc/3.x/functions/attribute.html

像这样:

{%set module="Electrocinetics" %}

Mark:{{attribute(mark, module)}}

游乐场示例:
https ://twigfiddle.com/1digwh

相关文章:
使用 Twig 中的数组键访问数组值


推荐阅读