In Mustache, How to get the index of the current Section

前端 未结 13 1078
臣服心动
臣服心动 2020-12-13 03:52

I am using Mustache and using the data

{ \"names\": [ {\"name\":\"John\"}, {\"name\":\"Mary\"} ] }

My mustache template is:



        
13条回答
  •  天命终不由人
    2020-12-13 04:21

    In handlebars.js you can accomplish this with a helper function. (In fact, one of the advantages mentioned about handlebars here http://yehudakatz.com/2010/09/09/announcing-handlebars-js/ is that you can use helpers instead of having to rewrite the objects before calling the template.

    So, you could do this:

      var nameIndex = 0;
      Handlebars.registerHelper('name_with_index', function() {
        nameIndex++;
        return this.name + " is " + nameIndex;
      })
    

    And, then your template can be this:

    {{#names}}
    
  • {{name_with_index}}
  • {{/names}}

    Your data is the same as before, i.e.:

    { "names": [ {"name":"John"}, {"name":"Mary"} ] };
    

    And you get this output:

  • John is 1
  • Mary is 2
  • To make this really work, nameIndex needs to get reset each time the template is rendered, so to do that you can have a reset helper at the beginning of the list. So full code looks like this:

      var data = { "names": [ {"name":"John"}, {"name":"Mary"} ] };
      var templateSource = "
      {{reset_index}}{{#names}}
    • {{name_with_index}}
    • {{/names}}
    "; 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 can correctly render the template twice.)

提交回复
热议问题