带有破折号的 Twig 渲染数组键 [英] Twig render array key with a dash in it

查看:27
本文介绍了带有破折号的 Twig 渲染数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you render a value of the value of an array key when it has a dash in the name?

我有这个片段:

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

And it renders four['five-six'] fine. But throws an error on ['two-three'].

推荐答案

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

This cannot work, since you shouldn't be using native operators in variable names - Twig internally compiles to PHP so it cannot handle this.

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

For attributes (methods or properties of a PHP object, or items of a PHP array) there is a workaround, from the documentation:

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

When the attribute contains special characters (like - that would be interpreted as the minus operator), use the attribute function instead to access the variable attribute:

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

这篇关于带有破折号的 Twig 渲染数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆