Handlebars showing only first three items

2019-05-18 01:12发布

I have an extensive news source (JSON), but I need to show only first three news to the user at home page. Is there a way to discard from the fourth onwards? Something like:

{{#each news}}
  {{ if index <= 3 }}
    <h3>{{title}} - {{date}}</h3>
    <p>{{post}}</p>
  {{/if}}
{{/each}}

Is it possible with Handlebars only or do I need to use Javascript?

2条回答
时光不老,我们不散
2楼-- · 2019-05-18 01:28

you are going to need to use a Handlebar helper, handle bars does not do this type of conditional checking.

    Handlebars.registerHelper('arrayCheck', function (newsArray) {
        //Logic
    });
查看更多
老娘就宠你
3楼-- · 2019-05-18 01:46

I have modified your Handlebar to support a range you can define. In example you want to display 4 items but want to begin with the second one. Here you go:

/*
 * Item helper.
 *
 * @return n elements
 */
Handlebars.registerHelper('listItem', function (from, to, context, options){
    var item = "";
    for (var i = from, j = to; i < j; i++) {
        item = item + options.fn(context[i]);
    }
    return item;
});

Then just use the handlebar like this:

{{#listItem 2 6 articles}}
    {{> article }}
{{/listItem}}
查看更多
登录 后发表回答