2010-10-17 33 views
29

如何在迭代中獲取對當前元素的引用?用小鬍子迭代數組

{{#my_array}} 
    <p>{{__what_goes_here?__}}</p> 
{{/my_array}} 

我希望我只是忽略了明顯。

回答

50

根據the spec's changelog,隱含迭代器(.)在規範的V1.1.0中的溶液。實現至少v1.1.0的每個Mustache庫都應該支持這一點。

{{#array_of_strings}}<li>{{.}}</li>{{/array_of_strings}} 
+0

注意:數組必須有隱式鍵才能工作。當你的數組有索引時使用這個方法將導致輸出單詞'Array'的一個實例。 – Popnoodles 2013-01-06 08:56:37

9

我走開了我的代碼,想起了Ruby是鴨子式的。由於我的陣列串的,所有我需要的是:

{{#my_array}} 
    <p>{{to_s}}</p> 
{{/my_array}} 

我將在這裏希望留下這個問題,以節省別人一些時間。

22

從源代碼https://github.com/bobthecow/mustache.php

/** 
* The {{%IMPLICIT-ITERATOR}} pragma allows access to non-associative array data in an 
* iterable section: 
* 
*  $context = array('items' => array('foo', 'bar', 'baz')); 
* 
* With this template: 
* 
*  {{%IMPLICIT-ITERATOR}}{{#items}}{{.}}{{/items}} 
* 
* Would render as `foobarbaz`. 
* 
* {{%IMPLICIT-ITERATOR}} accepts an optional 'iterator' argument which allows implicit 
* iterator tags other than {{.}} ... 
* 
*  {{%IMPLICIT-ITERATOR iterator=i}}{{#items}}{{i}}{{/items}} 
*/