简体   繁体   中英

Accessing nested array with handlebars from JSON and loop through

How can I access the results of a nested array with handlebars?

I have this dummy data:

var data = [{
    articles : [{
        id : '0',
        url : 'foo',
        title : 'Foo',
        body : 'some foo bar',
        category : 'foo',
        tags : [
            'foo'
        ]
    }, {
        id : '1',
        url : 'foo-bar',
        title : 'Foo bar',
        body : 'more foo bar',
        category : 'foo',
        tags : [
            'foo', 'bar'
        ]
    }, {
        id : '2',
        url : 'foo-bar-baz',
        title : 'Foo bar baz',
        body : 'more foo bar baz',
        category : 'foo',
        tags : [
            'foo',
            'bar',
            'baz'
        ]
    }]
}, {
    users : [{
        name: 'Admin'
    }, {
        name: 'User'
    }]
}];

This my template file:

{{#each data.[0].articles}}
<article class="id-{{this.id}}">
  <h1><a href="/journal/{{this.url}}">{{this.title}}</a></h1>
  <div class="category"><a href="/category/{{this.category}}">{{this.category}}</a></div>
  <p>{{this.body}}</p>
  <!--<div class="tags"><a href="/tags/{{this.tags}}">{{this.tags}}</a></div>-->
  <div class="tags">
    <ul>
      {{#each ../tags}}
      <li><a href="/tags/{{this}}">{{this}}</a></li>
      {{else}}
    </ul>
  </div>
</article>

{{else}}
<p class="empty">No content</p>
{{/each}}

If I use:

<div class="tags"><a href="/tags/{{this.tags}}">{{this.tags}}</a></div>

Than they will inserted as a whole. Is there a way to access them one by one?

Thank You!

My bad, it was syntax error. I didn't closed the nested each with {{/each}} but I used {{else}} instead.

{{#each data.[0].articles}}
<article class="id-{{this.id}}">
  <h1><a href="/journal/{{this.url}}">{{this.title}}</a></h1>
  <div class="category"><a href="/category/{{this.category}}">{{this.category}}</a></div>
  <p>{{this.body}}</p>
  <!--<div class="tags"><a href="/tags/{{this.tags}}">{{this.tags}}</a></div>-->
  <div class="tags">
    <ul>
      {{#each tags}}
      <li><a href="/tags/{{this}}">{{this}}</a></li>
      {{/each}}
    </ul>
  </div>
</article>

{{else}}
<p class="empty">No content</p>
{{/each}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM