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

前端 未结 13 1061
臣服心动
臣服心动 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:13

    A better approach for Mustache would be using a function that gets the index using indexOf:

    var data = { 
       names: [ {"name":"John"}, {"name":"Mary"} ],
        index: function() {
            return data.names.indexOf(this);
        }
    };
    
    var html = Mustache.render(template, data);
    

    In your template:

    {{#names}}
        {{name}} is {{index}}
    {{/names}}
    

    The drawback is that this index function has the array hard coded data.names to make it a more dynamic, we can use another function like this:

    var data = { 
       names: [ {"name":"John"}, {"name":"Mary"} ],
        index: function() {
            return function(array, render) {
                return data[array].indexOf(this);
            }
        }
    };
    
    var html = Mustache.render(template, data);
    

    Usage in your template:

    {{#names}}
        {{name}} is {{#index}}names{{/index}}
    {{/names}}
    

    Also a small drawback is that you have to pass the array name to the index function in this example names, {{#index}}names{{/index}}.

提交回复
热议问题