Twig 如何渲染包含破折号的数组键

17

当数组键名中含有破折号时,如何呈现该键名对应的值?

这是我目前的代码片段:

$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
这是因为 two-three 被用作局部符号,就像在原始的 PHP 中尝试使用 $two-three 一样。如果您像示例中那样使用 Twig,则应将该数组作为另一个数组的成员传递,并以变量名称作为键,例如 $data = array('values' => $theOtherArray); - prodigitalson
2个回答

30

由于您不应该在变量名中使用本地运算符,所以这无法工作。Twig内部编译为PHP,因此无法处理此类情况。

对于属性(PHP对象的方法或属性,或PHP数组的项),有一个解决方法,来自文档:

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

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

3
我猜你可以在Twig 2.x中使用{{ attribute(_context, 'data-foo') }}来处理非多维数组。 - norixxx

9

实际上这是可行的,而且它是有效的:

        $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"

这是一个不同的情况,嵌套在一个对象中。它并没有回答原始问题,仍然需要解决方法。 - Niels Keurentjes
1
谢谢。这是一种不错的处理破折号分隔键的方法。特别适用于快速传递众多表单数据项到电子邮件模板中,使用方便的破折号键。 - Valentine Shi
@NielsKeurentjes 嵌套一层深度 - 不会有太大的影响(这是我找到的唯一适用于破折号键的解决方案)。 - Playnox

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接