Reputation: 1353
I'm having trouble understanding how context works in handlebars.js, specifically the "../" notation. This is best exemplified by the jsfiddle I put together:
http://jsfiddle.net/accelerate/AwChe/
Context:
"rootvar": "hi",
"mydata": [{
"renderme": true,
"mytext": "bye"
}]
Template:
rootvar = {{{rootvar}}} (should be "hi")<br/>
{{#each mydata}}
<br/>In mydata...<br/>
rootvar = {{{rootvar}}} (should be empty)<br/>
rootvar = {{{../rootvar}}} (should be "hi")<br/>
mytext = {{{mytext}}} (should be "bye")<br/>
{{#if renderme}}
<br/>In renderme...<br/>
rootvar = {{{rootvar}}} (should be empty)<br/>
rootvar = {{{../rootvar}}} (should be empty)<br/>
rootvar = {{{../../rootvar}}} (should be "hi")<br/>
mytext = {{{mytext}}} (should be empty!!)<br/>
mytext = {{{../mytext}}} (should be "bye")<br/>
{{/if}}
{{/each}}
Output:
rootvar = hi (should be "hi")
In mydata...
rootvar = (should be empty)
rootvar = hi (should be "hi")
mytext = bye (should be "bye")
In renderme...
rootvar = (should be empty)
rootvar = (should be empty)
rootvar = hi (should be "hi")
mytext = bye (should be empty!!)
mytext = bye (should be "bye")
So in other words, I have an #if statement nested within an #each statement. I can see why I need to use "../../rootvar" to access "rootvar." What I don't understand is why I don't need to do do a "../" to access other variables within the current mydata element. Shouldn't I need to go to the #if's parent context to access "mytext", like I do for "rootvar"? And if I don't, then why does "../mytext" also work?
Upvotes: 0
Views: 370
Reputation: 5060
this is normal with #if
helper because it preserve the context.
//here context is:
// "rootvar": "hi",
// "mydata": [{
// "renderme": true,
// "mytext": "bye" }]
rootvar = {{{rootvar}}} (should be "hi")<br/>
{{#each mydata}}
// here `each` will change the context to each item in 'mydata' so it becomes
// { "renderme": true,
// "mytext": "bye" }
<br/>In mydata...<br/>
rootvar = {{{rootvar}}} (should be empty)<br/>
rootvar = {{{../rootvar}}} (should be "hi")<br/>
mytext = {{{mytext}}} (should be "bye")<br/>
{{#if renderme}}
// now `if` will create new context but it is the same as the parent context
// { "renderme": true,
// "mytext": "bye" }
<br/>In renderme...<br/>
rootvar = {{{rootvar}}} (should be empty)<br/>
rootvar = {{{../rootvar}}} (should be empty)<br/>
rootvar = {{{../../rootvar}}} (should be "hi")<br/>
mytext = {{{mytext}}} (should be "bye")<br/>
mytext = {{{../mytext}}} (should be "bye")<br/>
{{/if}}
{{/each}}
see this github issue for more details.
Upvotes: 1