Index of an array element in Mustache.js

前端 未结 6 962
后悔当初
后悔当初 2020-12-06 01:31

This is what I\'d like to do in Mustache.js but not seeing how with the documentation.

var view = {items:[\'Mercury\',\'Venus\',\'Earth\',\'Mars\']};
var tem         


        
6条回答
  •  被撕碎了的回忆
    2020-12-06 01:57

    Looking for a fast clean solution?

    Simply add an index function

    var data = {
        items: [{
                name: Aliasghar
                , grade: 19
            }, {
                name: Afagh
                , grade: 20
        }]
        , index: function() {
            return ++window['INDEX']||(window['INDEX']=0);
        }
    }
    

    and your template could be like this:

    {{#items}}
        {{index}} -- {{name}} is {{grade}}
    {{/items}}
    

    How it works

    We add a index: function(){} to data and we use it as a normal function in template. This function adds a key to the window object which is available globally; then increases it one by one.

    To use with multiple lists

    Please note that if you are using multiple templates one after another you need to either reset window['INDEX'] or change it's key to something else like window['YEKI_DIGE']. Another way of doing this is by adding a resetIndex function. Here is the way:

    var data = {
        items: [{
                name: Aliasghar
                , grade: 19
            }, {
                name: Afagh
                , grade: 20
        }]
        , index: function() {
            return ++window['INDEX']||(window['INDEX']=0);
        }
        , resetIndex: function() {
            window['INDEX']=null;
            return;
        }
    }
    

    and your template could be like this:

    {{#items}}
        {{index}} -- {{name}} is {{grade}}
    {{/items}}
    {{resetIndex}}
    

    Inspired by this answer: https://stackoverflow.com/a/10208239/257479 from dave on In Mustache, How to get the index of the current Section

提交回复
热议问题