Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Created February 5, 2013 00:06
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save amatiasq/4710958 to your computer and use it in GitHub Desktop.
Save amatiasq/4710958 to your computer and use it in GitHub Desktop.
This allow Handlebars to look up Backbone Model's attributes: {{ user.address.street }} If user is a Backbone Model this will become user.get("address").street And if user.get("adress") is also a Backbone Model this will be produced: user.get("address").get("street")
Handlebars.JavaScriptCompiler.prototype.nameLookup = function(parent, name, type) {
var result = '(' + parent + ' instanceof Backbone.Model ? ' + parent + '.get("' + name + '") : ' + parent;
if (/^[0-9]+$/.test(name)) {
return result + "[" + name + "])";
} else if (Handlebars.JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
return result + "." + name + ')';
} else {
return result + "['" + name + "'])";
}
};
@amatiasq
Copy link
Author

amatiasq commented Feb 5, 2013

Tested with Handlebars 1.0.rc.1

@amatiasq
Copy link
Author

amatiasq commented Feb 5, 2013

WARNING: Don't use it if Backbone.Model isn't global, it will broke all the templates.

@amatiasq
Copy link
Author

amatiasq commented Feb 5, 2013

Handlebars exposes this function in order to allow us to overwrite it.

@philihp
Copy link

philihp commented Oct 1, 2013

I love this. Thank you!

@ptbrowne
Copy link

ptbrowne commented Jan 9, 2014

Great ! Thank you !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment