Search code examples
backbone.jsmustachemodel-associations

Access Nested Backbone Model Attributes from Mustache Template


I have one Backbone model which has an attribute that is a reference to another Backbone model. For example, a Person has a reference to an Address object.

Person
  FirstName
  LastName
  Address
    Street
    City
    State
    Zip

These are classes that extend the Backbone model. So, then if I construct an object like the following...

var address = new Address({ Street: "123 Main", City: "Austin" });
var person = new Person({ FirstName: "John", Address: address });

I cannot seem to figure out how to access it in my Mustache template.

Hi {{FirstName}}, you live in {{Address.City}}.

Obviously does not work. When I look at the internals in Firebug, Address is an object, but the City is an attribute within the attributes object of Address. I cannot find any examples of how to access these attributes of associated objects.

I appreciate any help! Thanks!


Solution

  • Try using Handlebars, a templating engine based on Mustache with nested properties support.

    Then it would be as easy as {{Address/City}}.

    If you don't want to change your templating engine, you can flatten results from Address object and pass them as properties directly on the Person.