Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Backbone Model properties in a Handlebar template

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.

like image 310
Akshay Rawat Avatar asked Jan 05 '13 09:01

Akshay Rawat


2 Answers

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>
like image 175
jevakallio Avatar answered Nov 07 '22 08:11

jevakallio


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
like image 34
A. Matías Quezada Avatar answered Nov 07 '22 07:11

A. Matías Quezada