Index of an array element in Mustache.js

前端 未结 6 960
后悔当初
后悔当初 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:50

    If you want to access the index multiple times per item, I would suggest something like the following.

    var data = {
        items: [{
            name: Aliasghar
            , grade: 19
        }, {
            name: Afagh
            , grade: 20
        }]
        , setUpIndex: function() {
            ++window['INDEX']||(window['INDEX']=0);
            return;
        }
        , getIndex: function() {
            return window['INDEX'];
        }
        , resetIndex: function() {
            window['INDEX']=null;
            return;
        }
    }
    
    • Use the restIndex function before iterating each list in Mustache.
    • Use the setUpIndex function at the start of each list item to set up the index for that item.
    • Use the getIndex item to access the index.

    As an example, consider this.

    {{resetIndex}}
    {{#items}}
        {{setUpIndex}}
        {{getIndex}}. {{name}} is at index {{getIndex}}
    {{/items}}
    

    Notice how you can access index more than once per item without getting the wrong value.

提交回复
热议问题