Lanti
Lanti

Reputation: 2339

Loop through dummy data not showing up in Express app

I have this handlebars template file in my Express app:

{{#each data}}
<article class="id-{{this.id}}">
    <h1><a href="/journal/{{this.url}}">{{this.title}}</a></h1>
    <p>{{this.body}}</p>
</article>

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

This is the router:

router.get('/', function(req, res, next) {
    res.render('blog-index', {
        layout: 'main',
        title: 'Journal',
        data: articles
    });
});

If I use this javascript loop for dummy data, it showing the content without problem:

var 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'
    ]
}];

However if I using the following dummy data nothing shows up:

var articles = [{
    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'
    }]
}];

I modified the template file to this:

{{#each data.articles}}
<article class="id-{{this.id}}">
    <h1><a href="/journal/{{this.url}}">{{this.title}}</a></h1>
    <p>{{this.body}}</p>
</article>

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

What am I doing wrong?

Upvotes: 0

Views: 68

Answers (1)

Ryan
Ryan

Reputation: 5973

You have two levels of articles. So you would have to do something like this to get down to the second one:

{{#each data.0.articles}}
    <article class="id-{{this.id}}">
        <h1><a href="/journal/{{this.url}}">{{this.title}}</a></h1>
        <p>{{this.body}}</p>
    </article>

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

Note if you didn't have the second articles you would need to include square brackets around the index: {{#each data.[0]}}

See segment-literal syntax: http://handlebarsjs.com/expressions.html

Upvotes: 1

Related Questions