Search code examples
javascriptbackbone.jsunderscore.jsbackbone-viewsbackbone-model

write all backbone model attributes to html template


I am using a backbone view to write out model data to a template.

I am currently doing this in the view:

    return Backbone.View.extend({
        className: 'presentationListItem',
        template: _.template(tmpl, null, { variable: 'm' }),

        render: function() {
        this.$el.html(this.template(_.extend({}, this.model.toJSON())));
        return this;
}

And then in my HTML template, I access the data like this:

Catalog ID: {{ m.Id }} <br />
Catalog Name: {{ m.Name }} <br />

Lately, I've been having to pass different models through this view with different attributes.

I was wondering if there's a way to just write out everything in the model to the HTML template without having to specify specific attributes(ie ctx.Id, ctx.Name) like I'm doing now.

Thanks


Solution

  • If you want to pass multiply models to the view you can do it like this:

    Inside you view:

    template: _.template(tmpl)
    ...
    
    render: function() {
            this.$el.html(this.template({
               model1: this.model1.toJSON(),
               model2: this.model2.toJSON()}));
            return this;
    }
    

    And your template:

    Catalog ID: {{ model1.Id }} <br />
    Catalog Name: {{ model2.Id }} <br />