16

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

我有这个片段:

$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'].

4

2 回答 2

27

这是行不通的,因为您不应该在变量名中使用本机运算符 - Twig 在内部编译为 PHP,因此无法处理此问题。

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

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

{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}
于 2013-05-06T22:58:13.517 回答
7

实际上这可以工作,并且可以工作:

        $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"
于 2015-07-01T22:49:22.257 回答