Access Nested Backbone Model Attributes from Mustache Template

后端 未结 4 791
不思量自难忘°
不思量自难忘° 2020-12-28 21:50

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.

P         


        
相关标签:
4条回答
  • 2020-12-28 22:18

    The way to go about the same in Mustache would be as follows:

    Hi

    {{FirstName}}, you live in {{#Address}}{{City}} {{/Address}}
    

    Hope it helps..

    0 讨论(0)
  • 2020-12-28 22:27

    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.

    0 讨论(0)
  • 2020-12-28 22:27

    I handled this by making another version of toJSON called deepToJSON that recursively traverses nested models and collections. The return value of that function can then be passed to a handlebars.js template.

    Here is the code:

    _.extend(Backbone.Model.prototype, {
      // Version of toJSON that traverses nested models
      deepToJSON: function() {
        var obj = this.toJSON();
        _.each(_.keys(obj), function(key) {
          if (_.isFunction(obj[key].deepToJSON)) {
            obj[key] = obj[key].deepToJSON();
          }
        });
        return obj;
      }
    });
    
    _.extend(Backbone.Collection.prototype, {
      // Version of toJSON that traverses nested models
      deepToJSON: function() {
        return this.map(function(model){ return model.deepToJSON(); });
      }
    });
    
    0 讨论(0)
  • 2020-12-28 22:31

    I ended up solving this issue with the following approach.

    I switched from Mustache.js to Handlebars.js for the templating engine. This allowed me to use path based expressions to access nested or associated objects and their attributes.

    Hi {{FirstName}}. You live in {{Address.City}}.
    

    But, I also had to change the way I was passing a JSON object to the template. I was using the toJSON method that is part of the Backbone.Model class. But, this was not generating JSON for the associated Address correctly (for the templating to work.) It was burying the address attributes in a member titled "attributes". So, instead, I ended up doing this...

    var jsonForTemplate = JSON.parse(JSON.stringify(person));
    

    This gave me a "raw" version of the objects and their associated objects which the template could access using the syntax shown above. JSON.parse and JSON.stringify are both part of json2.js.

    0 讨论(0)
提交回复
热议问题