Documentation seems a bit sparse, so here is the low down:
- add the EJS gem (by Sam Stephenson, of Prototype fame) to your gemfile:
1
gem 'ejs'
- 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>
- 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
- (optional) EJS uses ERB syntax of <%= %> by default, but I preferred the syntax, so I added this into config/initializers/ejs.rb:
if you don’t want to do this, just use <%=variableName%> instead of1 2
EJS.evaluation_pattern = // EJS.interpolation_pattern = //
- 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'] });
- 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); });
- 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});
- I did have to force templates to be included before my backbone javascript by explicitly specifying it first in app.js: