javascript 访问 Handlebar.js 模板中的根上下文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17364897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access to root context in Handlebar.js template
提问by isHristov
Is there any built-in method for accessing the root context in a Handlebars.js template? Most of the helpers are adding a nested context and you have to write ../ before the variable in that context to access it but that is not very practical if you have lots of eachs, ifs, etc.
是否有任何内置方法可以访问 Handlebars.js 模板中的根上下文?大多数助手都在添加嵌套上下文,您必须在该上下文中的变量之前编写 ../ 才能访问它,但如果您有很多 eachs、ifs 等,这不是很实用。
回答by jaegow
Use @root. This is in handlebars-v2.0.0.js
使用@root。这是在handlebars-v2.0.0.js
{{@root.somthing.nested_somthing}}
回答by equivalent8
there is no possibility to access root context of template once you change the context with looping (e.g. each) more info
一旦您使用循环(例如每个)更多信息更改上下文,就无法访问模板的根上下文
However there is a possibility to access previous context with '../'
但是,有可能访问以前的上下文 '../'
# app/assets/javascript/contents.coffee
body = HandlebarsTemplates['my_hbs_template']({
view:{
registryName: 'foo',
data: {items: {x: 'x'}}
}
})
template:
模板:
<!-- app/assets/javascript/templates/my_content.hbs -->
<table class="table">
<tbody>
{{#each view.data.items}}
<tr>
<td>{{@key}}</td>
<td>
Hello from {{../view.registryName}}
</td>
</tr>
{{/each}}
</tbody>
</table>
check http://handlebarsjs.com/#pathsfor more info
检查http://handlebarsjs.com/#paths了解更多信息
回答by Mike Griffin
Yes, I have created one see http://www.my2ndgeneration.com/TemplateLanguageDoc.aspx#xroot
是的,我创建了一个见http://www.my2ndgeneration.com/TemplateLanguageDoc.aspx#xroot
Basically, add this helper and bingo {{xRoot}} will take you to the top ...
基本上,添加这个助手,宾果游戏 {{xRoot}} 将带你到顶部......
I always pass my JSON data into handlebars like this:
我总是像这样将我的 JSON 数据传递到车把中:
{ data: self.data }
thus the code below always returns "data" when it sees the xRoot tag and takes me to the top
因此,下面的代码在看到 xRoot 标记并将我带到顶部时总是返回“数据”
Handlebars.JavaScriptCompiler.prototype.nameLookup = function (parent, name, type) {
if (name.indexOf("xRoot") === 0) {
return "data";
}
if (/^[0-9]+$/.test(name)) {
return parent + "[" + name + "]";
} else if (Handlebars.JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
return parent + "." + name;
}
else {
return parent + "['" + name + "']";
}
};
回答by sidonaldson
Not as yet!
还没有!
It has been suggested a few times and there is an open ticket: https://github.com/wycats/handlebars.js/issues/392
已经被建议了几次,并且有一个公开票:https: //github.com/wycats/handlebars.js/issues/392
Their argument is that it isn't required but if it is a cheap fix with no discernible performance overhead I don't see why it can't be included.
他们的论点是它不是必需的,但如果它是一个没有明显性能开销的廉价修复,我不明白为什么不能包含它。