无法理解handlebars.js上下文

时间:2013-03-16 03:53:26

标签: javascript templates handlebars.js mustache

我无法理解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元素中的其他变量。我不应该去#if的父上下文访问“mytext”,就像我为“rootvar”做的那样吗?如果我不这样做,为什么“../mytext”也有效?

1 个答案:

答案 0 :(得分:1)

这对#if助手来说是正常的,因为它保留了上下文。

//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}}

有关详细信息,请参阅此github issue