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

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

    As long as you're not traveling into more than one array you can store the index on the helper and just increment when the context changes. I'm using something similar to the following:

    var data = {
        foo: [{a: 'a', 'b': 'a'}, {'a':'b', 'b':'b'}], 
        i: function indexer() {
            indexer.i = indexer.i || 0;
            if (indexer.last !== this && indexer.last) {                                          
                indexer.i++;
            }   
            indexer.last = this;
            return String(indexer.i);
         }   
    };
    
    Mustache.render('{{#foo}}{{a}}{{i}}{{b}}{{i}}{{/foo}}', data);
    

提交回复
热议问题