用胡子迭代数组

时间:2010-10-17 19:35:14

标签: ruby mustache

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

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

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

3 个答案:

答案 0 :(得分:55)

根据the spec's changelog,隐式迭代器(.)已添加到规范的v1.1.0中。每个至少实现v1.1.0的Mustache库都应该支持这个。

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

答案 1 :(得分: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}}
 */

答案 2 :(得分:9)

我离开了我的代码一段时间,并记得Ruby是鸭子类型。由于我的数组是字符串,我所需要的只是:

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

我会在这里留下这个问题,希望能有时间拯救别人。

相关问题