I have this object.
{
"myValue": 5
}
I wonder if it's possible to loop from 1...5 in mustache templates? Like this:
{{#myValue}}
{{.}}
{{/myValue}}
Prints:
12345
Expanding on @Thaylon's comment, you need an array to iterate through rather than a number. But assuming that changing myValue
from 5
to [1,2,3,4,5]
isn't an option, you can add a helper function that you can use in your template:
var ractive = new Ractive({
el: 'main',
template: '#template',
data: {
myValue: 5,
range: function ( low, high ) {
var range = [];
for ( i = low; i <= high; i += 1 ) {
range.push( i );
}
return range;
}
}
});
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>
<main></main>
<script id='template' type='text/ractive'>
{{#each range(1, myValue)}}
<p>{{this}}</p>
{{/each}}
</script>
As an alternative to putting the range()
helper on the data
object, you could add it as a generic helper by doing something like this:
var helpers = Ractive.defaults.data;
helpers.range = function ( low, high ) {
var range = [];
for ( i = low; i <= high; i += 1 ) {
range.push( i );
}
return range;
};
var ractive = new Ractive({
el: 'main',
template: '#template',
data: {
myValue: 5
}
});