You've got a lot of Gal

Yet another blog about Ruby, Rails, Javascript, Apple, Malteses and Shih-Tzus by Gal Steinitz

This site is completely static. It was last generated with Octopress and Jekyll on Sep 02, 2013 and hosted on github pages.

EJS Javascript Templates With Backbone JS and Rails 3.2.3

Documentation seems a bit sparse, so here is the low down:

  1. add the EJS gem (by Sam Stephenson, of Prototype fame) to your gemfile:
    1
    
    gem 'ejs'
    
  2. Assuming your backbone code is in app/assets/javsacripts/app and all javascript code is included automatically using asset pipleine’s “require tree”, add a template file in app/assets/javascripts/templates. For example for my video chat app, I followed the rails pattern of views//. I added app/assets/javascripts/templates/callers/show.jst.ejs:
    1
    2
    3
    4
    5
    6
    
    <div class='caller' id='caller-' data-stream-id=''>
      <div class='name'></div>
        <div id='stream-'>
        <div id='stream--replace'></div>
      </div>
    </div>
    
  3. I did have to force templates to be included before my backbone javascript by explicitly specifying it first in app.js:
    1
    2
    
    //=require_tree ./templates
    //=require_tree ./app
    
  4. (optional) EJS uses ERB syntax of <%= %> by default, but I preferred the syntax, so I added this into config/initializers/ejs.rb:
    1
    2
    
    EJS.evaluation_pattern = //
    EJS.interpolation_pattern = //
    
    if you don’t want to do this, just use <%=variableName%> instead of
  5. The EJS gem makes all templates available as clientside functions in window.JST. Add this at the top of your backbone view:
    1
    2
    3
    
      app.views.CallerIndexView = Backbone.View.extend({
        template: JST['templates/callers/show']
      });
    
  6. Now you can use it in your backbone view:
    1
    2
    3
    4
    5
    6
    7
    8
    
    app.views.CallerIndexView = Backbone.View.extend({
    
      template: JST['templates/callers/show'],
    
      render: function() {
        var html = this.template({name: stream.name, streamId: stream.streamId});
        this.$('#caller').append(html);
      });
    
  7. If you wanted to just test it out, you could just test it in a browser console like so:
    1
    2
    
    template = window.JST['templates/callers/show'];
    template({name: 'Joe', streamId: 1});