0

我无法理解上下文在 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”也有效?

4

1 回答 1

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 问题

于 2013-03-16T04:19:04.327 回答