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.
Use @root. This is in handlebars-v2.0.0.js
{{@root.somthing.nested_somthing}}
there is no possibility to access root context of template once you change the context with looping (eg 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/#paths for more info
Yes, I have created one see http://www.my2ndgeneration.com/TemplateLanguageDoc.aspx#xroot
Basically, add this helper and bingo {{xRoot}} will take you to the top ...
I always pass my JSON data into handlebars like this:
{ data: self.data }
thus the code below always returns "data" when it sees the xRoot tag and takes me to the top
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 + "']";
}
};
Not as yet!
It has been suggested a few times and there is an open ticket: 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.