Templates with Handlebars in Backbone.js

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

by Lucas Bittar Magnani

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.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!"}));
      }
  });
  

var AboutView = Backbone.View.extend({
      template: _.template( $("#about-template").html() ),      
      initialize: function () {
          this.render();
      },
      render: function () {
          this.$el.html(this.template({content:"As a front-end developer, I've always loved to build things..."}));
      }
  });
  
  var AppRouter = Backbone.Router.extend({
  		content: $("#content"),
      contentOut: {
      		marginTop: "20px",
      		opacity: 0
      },
      contentIn: {
      		marginTop: "0px",
      		opacity: 1
      },
      routes: {          
          '': 'homeRoute',
          'home': 'homeRoute',
          'about': 'aboutRoute',          
      },
      toggleViews: function (selectedView) {
      		var self = this;
      		self.content.animate(self.contentOut, 500, 'easeOutExpo', function(){
          		self.content.html(selectedView.el);
              self.content.animate(self.contentIn, 1000, 'easeOutExpo');
          });
      },
      homeRoute: function () {
          var homeView = new HomeView();          
          this.toggleViews(homeView);
      },
      aboutRoute: function () {
          var aboutView = new AboutView();
          this.toggleViews(aboutView);
      }
  });

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