ceth
ceth

Reputation: 45295

Iterate over array-field in the html-template

I have a collection of bookmark:

> db.Bookmarks.find()
{ "Name" : "Lenta.ru", "Timestamp" : 1381233418275, "URL" : "http://lenta.ru", "_id" : "zS2ccZXkGLENzN2Bx", "tags" : [  "asdx" ] }
{ "Name" : "Another", "Timestamp" : 1381234763188, "URL" : "http://ya.ru", "_id" : "qAB46c38hEFSw3NTE", "tags" : [  "one",  "two" ] }

The field 'tags' has type of array.

I have a HTML template to iterate over bookmarks:

<template name="bookmarks">
    {{#each bookmarks}}
          <a href="{{URL}}" class="bookmark_url">{{Name}}</a>
          <div> {{tags}} </div>
        {{/each}}
</template>

I want to display each tag into a separate 'div'. Something like this:

<template name="bookmarks">
    {{#each bookmarks}}
          <a href="{{URL}}" class="bookmark_url">{{Name}}</a>
          {{#each tags}}
             <div> {{current_tag}} </div>
          {{/each}}
        {{/each}}
</template>

How can I do it ?

Thanks.

Upvotes: 1

Views: 679

Answers (2)

matb33
matb33

Reputation: 2820

When iterating over a simple array, use {{this}} to access the value of each iteration.

{{#each tags}}
  <div>{{this}}</div>
{{/each}}

I recommend converting your tags array into an array of objects, such as:

"tags": [{_id: "1", "somevalue"}, {_id: "2", "someothervalue"}]

The Spark rendering engine is better able to decide when to redraw the content of an #each when unique IDs are involved. Reference: http://fogofcode.wordpress.com/2013/03/26/on-the-importance-of-_id-when-iterating-with-each-in-handlebarsmeteor/

Upvotes: 1

dimusic
dimusic

Reputation: 4133

{{#each current_tag in tags}}
    <div> {{current_tag}} </div>
{{/each}}

Upvotes: 0

Related Questions