In handlebars.js you can accomplish this with a helper function. (In fact, one of the advantages mentioned here about rudders here http://yehudakatz.com/2010/09/09/announcing-handlebars-js/ is that you can use helpers instead of rewriting objects before calling the template.
So you can do this:
var nameIndex = 0; Handlebars.registerHelper('name_with_index', function() { nameIndex++; return this.name + " is " + nameIndex; })
And then your template might be as follows:
{{#names}} <li>{{name_with_index}}</li> {{/names}}
Your data is the same as before, i.e.:
{ "names": [ {"name":"John"}, {"name":"Mary"} ] };
And you get this output:
<li>John is 1</li> <li>Mary is 2</li>
For this to work, nameIndex must receive a reset each time the template is rendered, so for this you can have a reset helper at the top of the list. Thus, the complete code is as follows:
var data = { "names": [ {"name":"John"}, {"name":"Mary"} ] }; var templateSource = "<ul>{{reset_index}}{{#names}}<li>{{name_with_index}}</li>{{/names}}</ul>"; var template = Handlebars.compile(templateSource); var helpers = function() { var nameIndex = 0; Handlebars.registerHelper('name_with_index', function() { nameIndex++; return this.name + " is " + nameIndex; }); Handlebars.registerHelper('reset_index', function() { nameIndex = 0; }) }(); var htmlResult= template(data); $('#target').html(htmlResult); var htmlResult2= template(data); $('#target2').html(htmlResult2);
(This may correctly display the template twice.)
mattsh Feb 22 2018-11-21T00: 00Z
source share