[英]Having trouble understanding handlebars.js context
I'm having trouble understanding how context works in handlebars.js, specifically the "../" notation. 我在理解上下文如何在handlebars.js中工作时遇到了麻烦,特别是“ ../”符号。 This is best exemplified by the jsfiddle I put together:
我放在一起的jsfiddle最好地体现了这一点:
http://jsfiddle.net/accelerate/AwChe/ 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. 换句话说,我在#each语句中嵌套了一个#if语句。 I can see why I need to use "../../rootvar" to access "rootvar."
我可以理解为什么我需要使用“ ../../rootvar”来访问“ 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.
我不明白的是为什么我不需要执行“ ../”来访问当前mydata元素中的其他变量。 Shouldn't I need to go to the #if's parent context to access "mytext", like I do for "rootvar"?
我是否不需要像#rootvar一样去#if的父上下文来访问“ mytext”? And if I don't, then why does "../mytext" also work?
如果我不这样做,那为什么“ ../mytext”也能起作用?
this is normal with #if
helper because it preserve the context. #if
helper这是正常的,因为它保留了上下文。
//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. 有关更多详细信息,请参见此github问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.