6

On initial page load, we are loading a large json data object with news feeds. We are using Mustache.js and listing all the new feed headlines which is working great.

We have a div area to display the details of the onClick news item. Since we have the data already loaded, I need to pass the index of the current item (array index) to grab the news item we need to get details from.

{{#Data}}
    <li>
       {{eventName}}<br />
       {{eventLocName}}<br />
       {{eventLocCity}}, {{eventLocST}}
    </li>
{{/Data}}

I would like to add an id to the

  • with the array index such as
    {{#Data}}
        <li id='{{Data.index}}'>
           {{eventName}}<br />
           {{eventLocName}}<br />
           {{eventLocCity}}, {{eventLocST}}
        </li>
    {{/Data}}
    

    What is the syntax to get array index into my Mustache.js template?

    UPDATED / WORKING

    Once I get my results onto the DOM, I used the following JS to add the 'index' into each array item. (select answer below code helped)

    for (i in result)
    result[i].index = i;
    
  • Ravi Ram
    • 24,078
    • 21
    • 82
    • 113

    3 Answers3

    5

    I'm sorry... I think you need to manually add index:

    for (i in Data)
       Data[i].index = i;
    

    and

    {{#Data}}
        <li id='{{index}}'>
           {{eventName}}<br />
           {{eventLocName}}<br />
           {{eventLocCity}}, {{eventLocST}}
        </li>
    {{/Data}}
    
    Luca
    • 4,223
    • 1
    • 21
    • 24
    1

    As far as I know you can't do that with Mustache.js, but you can do it with Handlebars.js which basically extends Mustaches functionality.

    You can simply import handlebars.js instead of mustache.js (since it uses the same syntax and has the same functionality but with some extras) and then do

    {{#each Data}}
        <li id='{{@index}}'>
           {{eventName}}<br />
           {{eventLocName}}<br />
           {{eventLocCity}}, {{eventLocST}}
        </li>
    {{/each}}
    

    Disclaimer: I'm far from an expert, so I wouldn't be surprised if you get a better answer.

    Ankur
    • 50,282
    • 110
    • 242
    • 312
    0

    Some Mustache implementations allow to do that (https://github.com/groue/GRMustache/blob/master/Guides/standard_library.md#each).

    You may ask the developer of your mustache library to support the feature.

    Gwendal Roué
    • 3,949
    • 15
    • 34