I just started with backbone.js, and one thing I noticed is that sometimes I donβt want the tagName contain / encapsulate my view template code. If I leave it in '' or 'span' , in my code I get unnecessary div and span .
An alternative I found is to remove the containing tag from my template ( <div class="photo_box"> in my example, as shown below), and use it as tagName in my view. In most cases, this tag will contain the class ( .photo_box ), and I still need to do addClass to (this.el). I don't like scattering template code.
Is there another way?
Js
// Views PhotoListView = Backbone.View.extend({ tagName: 'span', render: function() { _.each(this.model.models, function(photo) { $(this.el).append(new PhotoListItemView({ model: photo }).render().el); }, this); return this; } }); PhotoListItemView = Backbone.View.extend({ tagName: 'span', template: _.template($('#tpl-PhotoListItemView').html()), render: function() { $(this.el).html(this.template( this.model.toJSON() )); return this; } });
HTML
<script type="text/template" id="tpl-PhotoListItemView"> <div class="photo_box"> <div class="photo_container"> <img src="img/profiling/<%= photo_id %>.jpg" class='photo' /> </div> </div> </script>
Result
<div id="photo_list"> <span> <span> <div class="photo_box"> <div class="photo_container"> <img src="img/profiling/f_001.jpg" class="photo"> </div> </div> </span> <span> <div class="photo_box"> <div class="photo_container"> <img src="img/profiling/f_002.jpg" class="photo"> </div> </div> </span> </span> </div>
source share