我无法理解上下文在 handlebars.js 中的工作方式,特别是“../”符号。我放在一起的 jsfiddle 最好地说明了这一点:
http://jsfiddle.net/accelerate/AwChe/
语境:
"rootvar": "hi",
"mydata": [{
"renderme": true,
"mytext": "bye"
}]
模板:
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}}
输出:
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")
所以换句话说,我有一个嵌套在#each 语句中的#if 语句。我明白为什么我需要使用“../../rootvar”来访问“rootvar”。我不明白为什么我不需要做一个“../”来访问当前 mydata 元素中的其他变量。我不应该像访问“rootvar”那样访问#if 的父上下文来访问“mytext”吗?如果我不这样做,那么为什么“../mytext”也有效?