daytonn
12/12/2012 - 8:45 PM

EJS template compilation

EJS template compilation

Backbone uses JavaScript template functions to render views on the client-side. To be able to create individual template files that can be compiled into these template functions we need a gem, an erb template and a rake task.

The ruby-ejs gem

The ruby-ejs gem will compile a string or file template into a JavaScript template. This will be used to compile the individual templates placed in app/assets/javascripts/templates/**.* into template functions used in the application.

The ERB template

To compile the individual template functions generated by ruby-ejs into a JavaScript object, an ERB template file is used to create a templates.js file. The erb template file is located at lib/assets/compiled_templates.erb. This template simply creates an application namespace if one doesn't exist and adds the string of template functions created by the rake file to a <app_name>.Templates object. The source code for this template is simple:

var <%= "#{Rails.application.class.parent_name}" %> = <%= "#{Rails.application.class.parent_name}" %> || {};
<%= "#{Rails.application.class.parent_name}" %>.Templates = <%= templates %>;

The rake file

The rake file located at lib/assets/tasks/jstemplates.rake is responsible for taking the templates located at app/assets/javascripts/templates, recursively adding directories and template functions as a nested hash, and creating a javascript file with the hash and ERB the template. The task has two commands jst:build and jst:watch

To build the templates simply type: rake jst:build

This will build all of the templates and create a fresh template file at app/assets/javascripts/templates.js

If you wish to build template files on-demand as you create and edit templates, use the watch task: rake jst;watch

This will watch the app/assets/javascripts/templates directory for changes and compile a new templates.js automatically when changes occur.

EJS templates

EJS templates are a port of the Underscore.js template function which has a simlilar syntax to ERB

The EJS tag syntax is as follows:

  • <% ... %> silently evaluates the statement inside the tags.
  • <%= ... %> evaluates the expression inside the tags and inserts its string value into the template output.
  • <%- ... %> behaves like <%= ... %> but HTML-escapes its output.

If you have the ExecJS library and a suitable JavaScript runtime installed, you can pass a template and an optional hash of local variables to EJS.evaluate:

EJS.evaluate("Hello <%= name %>", :name => "world")
# => "Hello world"

This simple setup keeps the client-side template system clean and organized, and easy to maintain.