2013-05-06 58 views
11

如何在名稱中有一個短劃線時呈現數組鍵值的值?小枝渲染陣列鍵中有一條破折號

我有這樣的片段:

$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']上拋出錯誤。

+0

那是因爲'兩three'被用作局部符號..它像試圖使用'$兩個three'原始的PHP。如果你在你的例子中使用Twig,那麼你應該把數組作爲另一個數組的成員,並且使用變量名作爲關鍵字,比如'$ data = array('values'=> $ theOtherArray);' – prodigitalson 2013-05-06 22:54:33

回答

18

這不能工作,因爲你不應該在變量名稱中使用本地操作符 - Twig內部編譯爲PHP,因此它無法處理此操作。

對於屬性(方法或PHP對象的屬性,或PHP數組中的項)有一種變通方法,from the documentation:

當屬性包含特殊字符(如 - 這將是 解釋爲減運算符),使用屬性函數而不是 訪問變量屬性:

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

我想你可以使用'{{屬性(_context,'data-foo')}}'爲非多維數組@twig 2.x. – norixxx 2018-02-04 02:10:56

5

其實這可以工作,它的工作原理:

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

這是一個不同的情況,嵌套在一個對象中。它不回答仍然需要解決方法的原始問題。 – 2018-02-04 08:34:56