Handlebars showing only first three items

2019-05-18 00:40发布

问题:

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?

回答1:

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
    });


回答2:

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