Question

How do I obtain a reference to the current element in the iteration?

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

I hope I am just overlooking the obvious.

Was it helpful?

Solution

According to the spec's changelog, the implicit iterator (.) was added in v1.1.0 of the spec. Every Mustache library that implements at least v1.1.0 should support this.

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

OTHER TIPS

From the source code 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}}
 */

I walked away from my code for a bit and remembered that Ruby is duck typed. Since my array was of strings, all I needed was:

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

I'll leave this question here in the hopes to save somebody else some time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top