簡體   English   中英

無法理解handlebars.js上下文

[英]Having trouble understanding handlebars.js context

我在理解上下文如何在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”也能起作用?

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

有關更多詳細信息,請參見此github問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM