Add root context to data when using in-built #each and #which helpers#525
Add root context to data when using in-built #each and #which helpers#525williamcoates wants to merge 2 commits intohandlebars-lang:masterfrom
Conversation
…ions.data.root when using base #each and #which helpers
|
Does this mean in templates you could use |
|
No, its just adds root to the context so your helpers can use it |
|
You guys are off your game, it's easy ... 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 + "']";
}
};By the way, I've built a tool that allows you to execute full Handlebar templates on the desktop, without a browser, it's pretty cool |
|
👍 would be nice to see this merged |
|
Thanks for the PR and sorry it took me so long to look at this. We're going to do something like this but I want it to be generically accessible rather than just within these helpers. I've attached a PR to #392 to this end. |
|
So how would use use this? I guess it's @root ? I would have thought you would have been {{root}} or {{root.Items}} Can you show us how you would use root to get back up to the root of the data and access some properties? |
Sometimes you need to access variables from the root context in any other sub-context. It can be very painful having to always figure out the right path back to the root context when in multiple loops.
For example in my app i have an i18n object bound to the root context, that my i18n helper needs to access. If I can't easily access the root context i need to workaround this by backing up the context like so
This is painful, and not always possible if the above code is in a partial which might be used from different contexts.
This patch simply adds the root context to the data hash in the #each and #which helpers, so you can build helpers which access the root context like so:
It would be even cooler if you could do this in your templates:
But this would require altering the parser AFAIK which would require a bit more work...
Not sure on the etiquette for updating the distro, so I left those unchanged in this commit.