Adrian Florescu
Adrian Florescu

Reputation: 4492

Handlebars: pass the index of each to a nested expresstion

Is there any way to pass the each index or key to the nested expression in handlebars?

    //Not working
    {{#each thumbs}}
        <img src="{{src}} data-large="{{../[email protected]}}" alt="">
    {{/each}}

    //Working with manual passed array index
    {{#each thumbs}}
        <img src="{{src}} data-large="{{../images.2.src}}" alt="">
    {{/each}}

Playground: https://codepen.io/anything/pen/LZxwVL

Upvotes: 1

Views: 243

Answers (2)

hashchange
hashchange

Reputation: 7225

You can do that with the lookup helper and subexpressions.

The lookup helper can get you the hash of an image at a given index in your each loop. On that object, you need to lookup the src property. So here goes:

{{#each this.thumbs}}
  <p>SRC: {{src}}</p>
  <p>LARGE SRC:{{lookup (lookup ../images @index) "src"}} 
{{/each}}

You can see it at work in your modified demo.

Upvotes: 2

Eytibi
Eytibi

Reputation: 545

I created a custom helper method to achieve this:

/**
 * Iterates over an array (like the native {{each}} helper,
 * but adds to properties to each object: "_index" (a 0-based index) and "_position" (1-based index)
 */
Handlebars.registerHelper('iter', function(context, options) {
    var fn = options.fn, inverse = options.inverse;
    var ret = "";

    if(context && context.length > 0) {
        for(var i=0, j=context.length; i<j; i++) {
            ret = ret + fn(_.extend({}, context[i], { _index: i, _position: i + 1 }));
        }
    } else {
        ret = inverse(this);
    }
    return ret;
});

This helper method simply adds to members (_index, _position) to the passed object. (I've chosen to prefix them to not accidentally overwrite existing members.)

You can use the template this way:

{{#each thumbs}}
    <img src="{{src}} data-large="{{../[email protected]}}" data-index"={{_index}}" data-position"={{_position}}" alt="">
{{/each}}

But, I don't think you need the _position here.

Upvotes: 0

Related Questions