3

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?

Diego Rio
  • 33
  • 1
  • 4

2 Answers2

7

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}}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
sebfitz
  • 71
  • 1
  • 2
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
    });
ckross01
  • 1,681
  • 2
  • 17
  • 26
  • 2
    Got it: `Handlebars.registerHelper('listFirstThree', function (context, options) { var ret = ""; for (var i = 0, j = 3; i < j; i++) { ret = ret + options.fn(context[i]); } return ret; });` – Diego Rio Jun 25 '13 at 15:13