Backbone.js Templates Without Logic or Interpolation

Joël Quenneville

Traditional Backbone.js templates typically interpolate a few values and have a little basic logic, but even the simplest of these templates knows too much. It is the view’s responsibility to manage logic, events, and the relationship with models while the template should simply manage the HTML markup.

Enter the static template. It does not contain any logic or even interpolated values. In fact, a static template does not contain any executable code at all, it is just markup.

A static template and its view might look like this:

# app/assets/templates/profile_details.jst.ejs
<div class="status"></div>
<div class="name"></div>
<div class="age"></div>

# app/assets/javascripts/views/profile_details.coffee
class MyApp.Views.ProfileDetails extends Backbone.View
  className: 'profile-details'
  initialize: ->
    @$el.html JST['path/to/template']

  render: ->
    @_setStatus()
    @_setStatusClass()
    @_setName()
    @_setAge()

  _setStatus: ->
    @$el.find('.status').text @model.status()

 _setStatusClass: ->
    if @model.status() is 'online'
      @$el.find('.status').setClass('green')
    else
      @$el.find('.status').setClass('red')

  _setName: ->
    @$el.find('.name').text @model.name()

  _setAge: ->
    @$el.find('.age').text @model.age()

Keeping all that logic in the view has several key advantages:

  1. Easier to test

Keeping all the logic in the view makes it much easier to test-drive that behavior. This in turn increases the quality of your code and gives you greater confidence to build and refactor.

  1. Doesn’t break event bindings

With traditional templates, re-rendering creates new DOM elements which requires re-binding events. The DOM for static templates, on the other hand, is only rendered once. This spells the end of your event re-binding troubles.

  1. Faster re-rendering

Static templates can significantly improve your re-rendering speeds. Rendering traditional templates was an all-or-nothing decision. However, By encapsulating all the logic into methods on the view, this becomes a much more granular decision. Arbitrary sections can be ‘re-rendered’ in response to events.

By keeping a strong separation of concerns between your views and templates, you end up with code that is cleaner, more modular, more readable, more performant, and easier to maintain. Give it a try, you will be surprised by the power and simplicity of this approach.

Learn more about Backbone best practices in our book Backbone.js on Rails.