Loop through dummy data not showing up in Express app

时间:2016-02-12 22:10:45

标签: javascript json node.js express handlebars.js

I have this handlebars template file in my Express app:

.container:hover .sigma{
    display: block;
}

This is the router:

{{#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}}

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

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

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

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

I modified the template file to this:

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

What am I doing wrong?

1 个答案:

答案 0 :(得分:1)

您有两个articles级别。所以你必须做这样的事情才能进入第二个:

{{#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}}

请注意,如果您没有第二个articles,则需要在索引周围加上方括号:{{#each data.[0]}}

请参阅segment-literal语法:http://handlebarsjs.com/expressions.html