Backbone Template

Standard fiddle

by Skooljester

HTML

<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<div id="search_container"></div>
<script type="text/template" id="search_template">
    <label><%= search_label %></label>
    <input type="text" id="search_input" />
    <input type="button" id="search_button" value="Search" />
        <button id="testButton">Test this</button>
</script>

CSS

#search_container {
    background:#484848;
}

JavaScript

SearchView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        //Pass variables in using Underscore.js Template
        var variables = { search_label: "My Search" };
        //template is equal to all the content contained with the #search_template
        //it will display regardless of what has the id, but having <script> there makes it not appear on the page
        //now compiles the variable as well
        var template = _.template( $("#search_template").html(), variables );
        //takes the content of template and changes the elements html to be that | inserts it within the element
        this.el.html( template );
    },
    events: {
        "click input[type=button]": "doSearch",
        "click #testButton" : "doTest"
    },
    doSearch: function( event ){
        // Button clicked, you can access the element that was clicked with event.currentTarget
        alert( "Search for " + $("#search_input").val() );
    },
    doTest : function( event ){
        alert( "Hello" );
    }
});
var search_view = new SearchView({ el: $("#search_container") });