Templates in Backbone.js

Simple example of templates in Backbone.js using underscore.js as the templating engine.

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<div id="navigation">
    <a href="#/home">Home</a>
    <a href="#/about">About</a> 
</div>    
<div id="content">
</div>

<script type="text/template" id="home-template">
    <h1>Home Page</h1>
    <%= greeting %>
</script>

<script type="text/template" id="about-template">
    <h1>About Page</h1>
    <%= content %>
</script>

SCSS

body { margin: 30px;}
body {font-family: Arial;}
h1{font-weight:bold;font-size:16px;}
p{margin:5px 0px 5px 0px;}
div{margin:15px;}
div a{margin:5px;}

JavaScript

var HomeView = Backbone.View.extend({
      template: _.template($("#home-template").html()),
      initialize: function () {
          this.render();
      },
      render: function () {
          this.$el.html(this.template({greeting:"Welcome to Backbone!"}));
      }
  });
  

var AboutView = Backbone.View.extend({
      template: _.template($("#about-template").html()),
      initialize: function () {
          this.render();
      },
      render: function () {
          this.$el.html(this.template({content:"As a software developer, I've always loved to build things..."}));
      }
  });
  
  var AppRouter = Backbone.Router.extend({
      routes: {          
          '': 'homeRoute',
          'home': 'homeRoute',
          'about': 'aboutRoute',          
      },
      homeRoute: function () {
          var homeView = new HomeView();          
          $("#content").html(homeView.el);
      },
      aboutRoute: function () {
          var aboutView = new AboutView();          
          $("#content").html(aboutView.el);
      }
  });

  var appRouter = new AppRouter();
  Backbone.history.start();