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

Pet*_*tah 14 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);
Run Code Online (Sandbox Code Playgroud)

输出是

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

而且它four['five-six']很好.但是会抛出错误['two-three'].

Nie*_*jes 22

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

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

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

{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}
Run Code Online (Sandbox Code Playgroud)

  • 我想你可以使用`{{ attribute(_context, 'data-foo') }}` 来表示非多维数组@twig 2.x。 (3认同)

Pla*_*nox 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);
Run Code Online (Sandbox Code Playgroud)

并在模板文件中使用片段:

{{ list["one-two"]}} - Returns: Array
{{ list["one-two"].title }} - Returns: "Hello world 2"
Run Code Online (Sandbox Code Playgroud)