Madbrush
Madbrush

Reputation: 397

How to get index of object in handlebars each block

I'm trying to implement simple quiz. I have first version when I created my html in javascript. Generating answers looked like this:

    for(var i in answers) {
        outAnswers += '<li data-answer="' + i + '">' + answers[i] + "</li>"; 
    }

Now I trying to use handlebars.js for this:

   <ul id="answers">
       {{#each choices}}
           <li>{{this}}</li>
       {/each}}
   </ul>

I don't know how I can check for correct answers in Handlebars version. Earlier I just added html data attribute and check if($(this).data('answer') === correctIndex)

My sample qestion looks like this:

{
 question: "This is example question", 
 choices: ["Answer1", "Answer2", "Answer3", "Answer4"], 
 correctAnswer: 0
}

Upvotes: 0

Views: 761

Answers (1)

76484
76484

Reputation: 8993

From http://handlebarsjs.com: "When looping through items in each, you can optionally reference the current loop index via {{@index}}". So to achieve with your template what you were achieving without it, your template would become:

<ul id="answers">
    {{#each choices}}
        <li data-answer="{{@index}}">{{this}}</li>
    {{/each}}
</ul>

Upvotes: 1

Related Questions