2010-11-01 11 views
9

在子區段中,鬍鬚可以從父區段讀取變量嗎?鬍鬚:從子區段的父區段讀取變量

比如我下面的例子,我想{{order_store.id}}讀取變量從它的父$ order_store [(當前子循環的數組索引)] [ '身份證']

the template.mustache

{{#order_store}}<table> 
    <caption> 
     Store Name: {{name}} 
     Product Ordered: {{products}} 
     Product Weights: {{products_weight}} 
    </caption> 
    <tbody> 
     {{#shipping_method}}<tr> 
      <td> 
       <input type="radio" name="shipping[{{order_store.id}}]" id="shipping-{{id}}" value="{{id}}" /> 
       <label for="shipping-{{id}}">{{name}}</label> 
      </td> 
      <td>{{description}}</td> 
      <td>{{price}}</td> 
     </tr>{{/shipping_method}} 
    </tbody> 
</table>{{/order_store}} 

sample data(in PHP);

   $order_store => array(
       array(
        'id' => 1, 
        'name' => 'Kyriena Cookies', 
        'shipping_method' => array(
         array(
          'id' => 1, 
          'name' => 'Poslaju', 
          'description' => 'Poslaju courier' 
         ), 
         array(
          'id' => 2, 
          'name' => 'SkyNET', 
          'description' => 'Skynet courier' 
         ), 
        ), 
       )); 

回答

7

鬍子不允許你引用父對象。您希望在子節中顯示的任何數據都需要包含在子數組中。

例如:

$order_store => array(
array(
    'id' => 1, 
    'name' => 'Kyriena Cookies', 
    'shipping_method' => array(
     array(
      'id' => 1, 
      'name' => 'Poslaju', 
      'description' => 'Poslaju courier', 
      'order_store_id' => '1' 
     ), 
     array(
      'id' => 2, 
      'name' => 'SkyNET', 
      'description' => 'Skynet courier', 
      'order_store_id' => '1' 
     ), 
    ), 
)); 

然後你可以使用標籤{{order_store_id}}

點符號在這種情況下不會有幫助 - 它不會奇蹟般地讓您訪問父數組。 (順便說一下,所有鬍鬚解析器都不支持點符號,所以如果有機會在將來想用其他編程語言重新使用您的模板,最好避免使用它。)

+0

其實,我會採取@sofia建議並使用Handlebar。 JS。它與小鬍子兼容,但添加了一些新功能,如在父上下文中進行搜索。我遇到了同樣的問題,Handlebar幫助我解決了這個問題,而無需更改我的json內容。 – 2013-07-30 22:12:35

+0

@GustavoCardoso問題是在PHP中尋找答案。 – 2014-03-25 20:50:22

+0

我已經在js **中嘗試了這個**,看起來好像小鬍子允許我通過引用它來引用父對象的屬性,**如果子數組中沒有重疊的名稱**(如果存在,小鬍子會拿起那個小孩)。不過,我還沒有測試過PHP中會發生什麼。 – Pere 2014-06-17 11:12:12

-2

的這裏的技巧是在您的模板開始補充:

{{%DOT-NOTATION}} 
+0

什麼?!?........ – 2016-07-12 13:34:24

5

如果模板可以在客戶端編譯,另一種選擇是使用HandlebarsJS模板,這是與鬍鬚兼容,使用父符號:

{{../order_store.id}} 
1

我有同樣的問題,用空的對象,它是不null

<div class="photo"> 
    {{#picture.id}} 
     <img src="{{picture.src}}" alt="{{picture.name}}" /> 
    {{/picture.id}} 
</div> 

你可以看到我可以在「if」語句中使用picture.id picture.src value