带有破折号的 Twig 渲染数组键

2022-08-30 23:05:21

当数组键的名称中有破折号时,如何呈现数组键的值?

我有这个片段:

$snippet = "
    {{ one }}
    {{ four['five-six'] }}
    {{ ['two-three'] }}
";

$data = [
    'one' => 1,
    'two-three' => '2-3',
    'four' => [
        'five-six' => '5-6',
    ],
];

$twig = new \Twig_Environment(new \Twig_Loader_String());
echo $twig->render($snippet, $data);

输出为

1
5-6
Notice: Array to string conversion in path/twig/twig/lib/Twig/Environment.php(320) : eval()'d code on line 34

而且它渲染得很好。但在 上抛出错误。four['five-six']['two-three']


答案 1

这不起作用,因为你不应该在变量名称中使用本机运算符 - Twig内部编译为PHP,因此它无法处理这个问题。

对于属性(PHP 对象的方法或属性,或 PHP 数组的项),有一个解决方法,从文档中可以看出:

当属性包含特殊字符(如 - 将被解释为减号运算符)时,请改用属性函数来访问变量属性:

{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}

答案 2

实际上,这可以工作,并且它的工作原理:

        $data = [
            "list" => [
                "one" => [
                    "title" => "Hello world"
                ],
                "one-two" => [
                    "title" => "Hello world 2"
                ],
                "one-three" => [
                    "title" => "Hello world 3"
                ]
            ]
        ];
        $theme = new Twig_Loader_Filesystem("path_to_your_theme_directory");
        $twig = new Twig_Environment($theme, array("debug" => true));
        $index = "index.tmpl"; // your index template file
        echo $this->twig->render($index, $data);

和在模板文件内使用的片段:

{{ list["one-two"]}} - Returns: Array
{{ list["one-two"].title }} - Returns: "Hello world 2"

推荐