Lean JavaScript templates in Rails

A little known Rails feature is built-in JST support and we can leverage this along with EJS to have a neat and tidy JS templating solution.

Getting started

The first thing you’ll want to do is add the ejs gem to your gemfile

gem 'ejs' # client side templates

Once we’re setup with EJS we can then create our first template:

// app/assets/javascripts/templates/profile.jst.ejs
<div class="user-profile">
  <img src="<%= user.profile_img %>">
  <h4><%= user.username %></h4>
</div>

To get templates loading into application.js, add //= require_tree ./templates like below:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree ./templates
//= require_tree .

All set, now each of the templates is available as a javascript variable with the path name of the template. The profile.jst.ejs template created above is available as JST['templates/profile']

// Example usage
$(function() {
  var profile_template = JST['templates/profile'];

  var html = profile_template({
    user: {
      username: "phawk",
      profile_img: "https://example.org/thumb/pete.jpg"
    }
  });

  $('.user-profiles').append(html);
});

We could accomplish something similar with a more complex solution like requireJS or browserify, however I like to keep my tooling and workflow lean when starting new projects and sticking with the asset pipeline is usually how I start off.

If you need help with your web or mobile application I’m a partner at Dawson Andrews, we specialise in digital strategy and product thinking, building rich web apps and native mobile apps.

comments powered by Disqus