daGUY
daGUY

Reputation: 28743

Using index value inside of a Handlebars each block

I have a Handlebars template that inserts an img element on my page. The image URLs come from an array that can have up to 8 items, but I only want to insert the first 4.

A simple {{#each}} block like this inserts an img for every item:

{{#each items}}
    <img src="{{item.url}}" />
{{/each}}

How do I "stop" the {{#each}} after the first 4 items? Or, put another way, how do I tell it to only insert the img element if its index in the array is less than 4 (0 through 3)?

I know I can output the current index with {{@index}}, but I can't seem to use that within an {{#if}} block. In other words, this doesn't work:

{{#each items}}
    {{#if {{@index}} < 4}}
    <img src="{{item.url}}" />
    {{/if}}
{{/each}}

What do I do instead?

Upvotes: 1

Views: 374

Answers (1)

76484
76484

Reputation: 8993

I think the simplest way would be to slice your array, .slice(0, 4), before you pass it to your compiled template function.

But if, for some reason, that is not an option, I suppose you would have to create a custom helper:

Handlebars.registerHelper('firstFour', function (context, options) {
    var result = '';
    var length = Math.min(context.length, 4);
    for (var i = 0; i < length; i++) {
        result += options.fn(context[i]);
    }

    return result;
});

And your template would look like this:

{{#firstFour items}}
    <img src="{{this.url}}" />
{{/firstFour}}

Upvotes: 2

Related Questions