[英]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.