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

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

    I'm using a pre calculate function to inject '@index' into array.

    const putIndexInArray = array => {
        let putIndex = (value, index) => {
            value['@index'] = index;
    
            return value;
        };
    
        if (!Array.isArray(array)) {
            return array;
        }
    
        return array.map(putIndex);
    };
    
    Mustache.render(template, {
        array: putIndexInArray(['Homer', 'Marge', 'Lisa'])
    });
    

    and then using like this:

    {{#array}}
        {{@index}}
    {{/array}}
    

提交回复
热议问题