Twig渲染数组键,其中带有破折号

时间:2013-05-06 22:50:21

标签: php twig

如果数组键的名称中包含短划线,如何呈现数组值的值?

我有这个片段:

$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']上会抛出错误。

2 个答案:

答案 0 :(得分:19)

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

对于属性(PHP对象的方法或属性,或PHP数组的项),有一种解决方法,from the documentation:

  

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

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

答案 1 :(得分:6)

实际上这可行,并且有效:

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