If there is a Backbone Model called Person
, which has properties firstName
, lastName
. Usually, access to it is like person.get('firstName')
and person.get('lastName')
.
How do I do a similar thing in a Handlebar template, where a person
has been exposed to the context.
When you render the Handlebars template, you need to pass in the attributes of the model. The recommended way to do this is to call Model.toJSON
, which returns a copy of the the model's internal attributes
hash.
var template = Handlebars.compile(templateHtml);
var rendered = template({ person: model.toJSON() });
In the template you can access the context by the property name.
<span>{{person.firstName}} {{person.lastName}}</span>
Actually I've so many places with .toJSON so I've developed a Handlebars modification to handle Backbone Models:
https://gist.github.com/4710958
It will check if a value is instance of Backbone.Model and if it is it will invoke the .get() method.
Backbone.Model should be global in order to use it.
{{ user.address.street }}
Will be parsed as:
user.get("adress").street
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With