简体   繁体   English

骨干网:如何将模板呈现为DOM?

[英]Backbone: How to render template to DOM?

I am new to Backbone and having difficulties with rendering a template. 我是Backbone的新手,在呈现模板时遇到困难。
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 . 我猜没什么特别的-只是一个简单的模型和一个使用模板的视图,将占位符替换为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? 当使用personView.el在控制台中进行检查时,会显示正确的HTML字符串,但应如何将其呈现给DOM?

Of course I already read through the Backbone and Underscore documentation, but I haven't found much regarding this. 当然,我已经阅读了Backbone和Underscore文档,但是对此却没有太多了解。

A backbone view contains a reference to an el which may or may not be part of the page's DOM. 骨干视图包含对el的引用,该el可能是也可能不是页面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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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