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>
I think the best solution to this is:
render: function(){
var html = this.template(this.model.toJSON()));
var newElement = $(html)
this.$el.replaceWith(newElement);
this.setElement(newElement);
return this;
}
Sorry For a late response and this may have already been solved. I find its best to try and make templates and views as easily as possible. I use Handlebars for my templates.
Each of your templates regardless of use will need to have an HTML element associated with them, so in your view pick whatever elements you want and remove that element from your template, instead of trying to go against the grain. You can then set the attributes in your view to mirror those of your removed template element.
var yourview = Backbone.View.extend({
{
tagName : *whatever element ( i.e. section, div etc ),
attributes : {
id : 'your element id'
class : 'your element class'
etc
},
})
Then in your template remove that element this this element will be created nicely without wrapping your template, rather than having to change your render method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With