Rails JS templates

Published on by   rails, javascript

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 template 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.

Related Articles

We’re currently working on a new Shopify app of our own which has allowed us to try out some cutting-edge technologies. Nearly all of the…

In a recent project I have been using UUIDs as the primary key type with Rails 5 and PostgreSQL. This can be useful if your objects IDs are…

Searching proximity to a location is a task we have done before in a traditional database with some complex trigonometry algorithms. As we…

Would you like to work with us?

We would love to hear from you

Get in touch

© Alternate Labs Ltd is a registered company in Northern Ireland NI628282