使用Mustache迭代数组

45

如何获取迭代中当前元素的引用?

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

我希望我只是忽略了显而易见的事情。

3个回答

76

根据规范的变更日志,在规范的v1.1.0版本中添加了隐式迭代器(.)。每个实现至少v1.1.0版本的Mustache库都应该支持此功能。

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

注意:为使此方法生效,数组必须具有隐式键。当您的数组具有索引时使用此方法将导致一个Array单词实例被输出。 - Popnoodles

23

从源代码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}}
 */

9

我暂时离开了我的代码,想起 Ruby 是鸭子类型的。由于我的数组是字符串类型的,所以我只需要:

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

我把这个问题留在这里,希望能为其他人节省一些时间。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接