1.

How Can You Use Underscore Templates In Backbone.js Views?

Answer»
  1. First, create an underscore template
  2. Create DIV for EL property of the view
  3. Compile the template using underscore
  4. Load the compiled HTML into Backbone “el”

See the below example:

<SCRIPT type="TEXT/template" id="search_template">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
// Compile the template using underscore
var template = _.template( $("#search_template").html(), {} );
// Load the compiled HTML into the Backbone "el"
this.$el.html( template );
}
});

var search_view = new SearchView({ el: $("#search_container") });
</script>

See the below example:

<script type="text/template" id="search_template">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
// Compile the template using underscore
var template = _.template( $("#search_template").html(), {} );
// Load the compiled HTML into the Backbone "el"
this.$el.html( template );
}
});

var search_view = new SearchView({ el: $("#search_container") });
</script>



Discussion

No Comment Found