1

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?

1 Answer 1

2

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}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.