简体   繁体   中英

Backbone: How to render template to DOM?

I am new to Backbone and having difficulties with rendering a template.
The template itself is as unspectacular as this:

<script id="messageTemplate" type="text/template">
    Message: <%= content %>
</script>

The Backbone view & model look like this:

var Message = Backbone.Model.extend({
    defaults: {
        content: 'Default message'
    }
});

var MessageView = Backbone.View.extend({
    tagName: 'p',
    template: _.template($('#messageTemplate').html()),
    initialize: function() {
      this.render();
    },
    render: function() {
      this.$el.html(this.template(this.model.toJSON()));
      return this;
    }
});

var msg = new Message();
var msgView = new MessageView({model: msg});

Nothing special I guess – just a simple model and a view using the template, replacing the placeholder with the content from msg .

When checking in the console with personView.el I get presented the correct HTML string, but how should I render it to the DOM?

Of course I already read through the Backbone and Underscore documentation, but I haven't found much regarding this.

A backbone view contains a reference to an el which may or may not be part of the page's DOM. If it isn't then you can attach it just as you would any other element.

For example

var msg = new Message();
var msgView = new MessageView({model: msg});
$('#someParentElement').append(msgView.el);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM