3

I looked for a duplicate question but couldn't find one on SO. Hence here it goes.

I have an #each block in my template which is successfully printing the values from an array but when I try to get the current index using @index within that block like this - {{@index}}, it's undefined.

From the official handlebars docs I found this way of getting the current index.

The Router (router.js) :

Router.map(function() {
    this.resource("books", function(){
        this.route("about", { path : "/:bookId"}, function(){

        });
    });
});

The Route (routes/books.js) :

var BooksRoute = Em.Route.extend({
    model: function() {
        return [{
            name: "Harry Potter & The Deathly Hallows"
        }, {
            name: "What If?"
        }, {
            name: "Diary of a Wimpy Kid"
        }, {
            name: "The Martian"
        }];
    }
});

export default BooksRoute;

The Template (templates/books/index.hbs) :

<div class="page-header">
    <h1>All Books!</h1>
    <ul>
        {{#each book in model}}
            {{@index}}
            <li>{{#link-to "books.about"}} {{book.name}} {{/link-to}}</li>
        {{/each}}
    </ul>
</div>

What I want to be able to do is to generate link to each book with the current index being used as the :bookId e.g. /books/1.

Is there anything wrong in my code? How can I make it work?

UPDATE : I have tried {{#each model as |book index|}} as well with no luck.

It works with {{#each model as |book index|}}. Problem was me doing {{@index}} instead of {{index}} with the new approach.

5
  • try using this {{#each model as |book index|}}{{index}} <li>{{#link-to "books.about"}} {{book.name}} {{/link-to}}</li> {{/each}}
    – blessanm86
    Jun 4, 2015 at 9:08
  • no luck. still undefined Jun 4, 2015 at 9:11
  • 1
  • yes it does work in the demo but not in my project? ! :( Jun 4, 2015 at 9:45
  • sorry. it does work. my bad. i was still trying to print {{@index}}. Thanks a lot. can you add that as an answer so i can accept it? Jun 4, 2015 at 9:46

1 Answer 1

6

Since ember 1.11.0 index support has been added to the each helper. You can use it like

{{#each model as |book index|}}
  {{index}}
        <li>{{#link-to "books.about" index}} {{book.name}} {{/link-to}}</li>
{{/each}}

Here is a working demo.

1
  • this also seems like a better approach than @index that index can now be passed to other things more naturally. Jun 4, 2015 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.