Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over arrays with mustache

Tags:

ruby

mustache

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.

like image 947
Jeremy Avatar asked Oct 17 '10 19:10

Jeremy


3 Answers

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}}
like image 124
pvande Avatar answered Nov 08 '22 02:11

pvande


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}}
 */
like image 24
ghindle Avatar answered Nov 08 '22 02:11

ghindle


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.

like image 9
Jeremy Avatar answered Nov 08 '22 02:11

Jeremy