Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars.js - Getting parent context within an each loop, an if statement and a child object

I understand how to transverse the data source within Handlebars but I have stumbled across a situation I cannot work out.

Using "../" you can reach the parent template scope but when iterating through the child of an object it seems to return the object and not the child.

{{#each content.items}}
{{#if prop}}
<p>{{prop}} + {{../../variable}}</p>
{{/if}}
{{/each}}

The above code snippet works fine if you iterate through an object called 'content' but as soon as you iterate through it's child, 'content.items' it no longer returns the right scope.

Here is a fiddle which demonstrates the issue. http://jsfiddle.net/sidonaldson/MDdn2/

Can anyone shed any light on what is wrong?

like image 679
sidonaldson Avatar asked Jul 30 '13 11:07

sidonaldson


1 Answers

It turns out that my original thought was wrong. I've only used Handlebars.js inside the context of Ember.js. Ember provides some extra helpers that aren't available in plain Handlebars, so that wasn't an option. But I did seem to figure out your issue. Check this fiddle.

<p>IN CONTENT</p>
{{#with content}}
{{#each items}}
{{#if prop}}
<p>{{prop}} + {{../../variable}}</p>
{{/if}}
{{/each}}
{{/with}}
<p>OUTSIDE CONTENT</p>
{{#each items}}
{{#if prop}}
    <p>{{prop}} + {{../../variable}}</p>
{{/if}}
{{/each}}

I'm not sure why it didn't work in the first place, but using the with helper, then the each helper seemed to work. Hopefully I've come close to what you wanted.

like image 149
GJK Avatar answered Oct 27 '22 03:10

GJK