[英]Twig render array key with a dash in it
當名稱中包含短划線時,如何呈現數組鍵值的值?
我有這個片段:
$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']
上拋出錯誤。
這不起作用,因為你不應該在變量名中使用本機運算符--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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.