Php 带有破折号的细枝渲染数组关键点

Php 带有破折号的细枝渲染数组关键点,php,twig,Php,Twig,当数组键的名称中有破折号时,如何呈现它的值 我有一段话: $snippet = " {{ one }} {{ four['five-six'] }} {{ ['two-three'] }} "; $data = [ 'one' => 1, 'two-three' => '2-3', 'four' => [ 'five-six' => '5-6', ], ]; $twig = new \Twig_E

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

我有一段话:

$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']
fine。但是在
['two-three']
上抛出一个错误,这无法工作,因为您不应该在变量名中使用本机运算符-Twig在内部编译为PHP,因此无法处理此问题

对于属性(PHP对象的方法或属性,或PHP数组的项),有一个变通方法

当属性包含特殊字符时(如-这将是 解释为减号运算符),请改用属性函数 要访问变量属性,请执行以下操作:

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

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

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

这是因为
two-three
被用作本地符号。。这就像在原始PHP中尝试使用
$two-three
。如果您使用的是示例中的Twig,那么您应该将数组作为另一个数组的成员传入,并将变量名作为键,如
$data=array('values'=>$theOtherArray)
我想你可以对非多维数组@twig 2.x使用
{attribute(_context,'data foo')}}
。它没有回答原来的问题,仍然需要解决。谢谢。这是一个很好的方法,知道如何做破折号分隔键。特别适用于快速将带有方便的虚线键的大量表单数据项传递到电子邮件模板。@NielsKeurentjes向下嵌套一级-不会有太大区别(这是我发现的唯一适用于虚线键的解决方案)