Lean JavaScript templates in Rails

October 21, 2016

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>

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"


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.

Pete Hawkins

Hey 👋 I’m Pete a web developer, who loves to ship products and build cool things with React and React Native.
You can follow me on Twitter or Subscribe for updates.