当名称中有破折号时,如何呈现数组键的值?
我有这个代码片段:
$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']
上抛出错误。
发布于 2013-05-07 06:58:14
这是行不通的,因为你不应该在变量名中使用本地操作符-- Twig在内部编译成PHP,所以它不能处理这个问题。
对于属性( PHP对象的方法或属性,或者PHP数组的项),有一个解决办法,from the documentation:
当属性包含特殊字符(如-,将被解释为减号运算符)时,请改用属性函数来访问变量属性:
{#等同于非工作foo.data-foo #} {{ (foo,'data-foo') }}属性
发布于 2015-07-02 06:49:22
实际上,这是可行的,而且是可行的:
$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"
https://stackoverflow.com/questions/16408559
复制相似问题