如何避免在 Backbone 中使用空 div 进行模板包装? [英] How to avoid template wrapping with empty div in Backbone?
问题描述
当我创建视图主干时,如果 el 未设置,则会创建空的 div 容器.模板 (this.$el.html(this.template(this.model.toJSON())))
插入到那个 div 中.如何避免这种包装?我需要没有任何包装的干净模板,以便我可以将它插入任何我想要的地方?用很多元素调用 jobView.$e.children()
是不合理的.
var JobView = Backbone.View.extend({模板:_.template($("#contactTemplate").html()),初始化:函数(){this.render();},渲染:函数(){this.$el.html(this.template(this.model.toJSON()));返回这个;}});var jobView = 新的 JobView({模型:工作模型});控制台日志(jobView.el);
我认为这个问题的真正答案还没有提供,只需从模板中删除 div
并添加 className
属性到 JobView
!这将产生您需要的标记:
模板:
视图:
var JobView = Backbone.View.extend({className: 'job',//当你渲染视图时,这个类会被添加到包装 div 中模板:_.template($("#contactTemplate").html()),初始化:函数(){this.render();},渲染:函数(){this.$el.html(this.template(this.model.toJSON()));返回这个;}});
当您调用 render
时,您将得到所需的标记:
<h1><%=标题%>/<%=类型%></h1><div><%=描述%></div>
When I create view backbone creates empty div-container if el is not set. Template (this.$el.html(this.template(this.model.toJSON())))
inserted in that div. How to avoid this wrapper? I need clean template without any wrappers so I can insert it anywhere I want? It's not reasonable to call jobView.$e.children()
with many elements.
<script id="contactTemplate" type="text/html">
<div class="job">
<h1><%= title %>/<%= type %></h1>
<div><%= description %></div>
</div>
</script>
var JobView = Backbone.View.extend({
template:_.template($("#contactTemplate").html()),
initialize:function () {
this.render();
},
render:function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var jobView = new JobView({
model:jobModel
});
console.log(jobView.el);
I think the real answer to this question has not been provided yet, simply remove the div
from the template and add the className
property to JobView
! This will result in the markup you require:
The template:
<script id="contactTemplate" type="text/html">
<h1><%= title %>/<%= type %></h1>
<div><%= description %></div>
</script>
The view:
var JobView = Backbone.View.extend({
className: 'job', // this class will be added to the wrapping div when you render the view
template:_.template($("#contactTemplate").html()),
initialize:function () {
this.render();
},
render:function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
When you call render
you will end up with the desired markup:
<div class="job">
<h1><%= title %>/<%= type %></h1>
<div><%= description %></div>
</div>
这篇关于如何避免在 Backbone 中使用空 div 进行模板包装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!