Integrating EJS Templates into Rails

I’ve been on few projects where we need to have client-side view templates. This would mostly involve making an AJAX request to the server, getting back some JSON data at which point we need to convert this into HTML. EJS is one of a number of solutions to this problem.

I’m not saying EJS is the best solution, but it’s straightforward to integrate, understand and use.

To start off, add the EJS gem to your Gemfile.

group :assets do
  gem 'ejs'

You can put your views anywhere inside ‘app/assets/javascripts’, so let’s create a view at ‘app/assets/javascripts/views’ and call it ‘index.jst.ejs’. The syntax is incredibly straightforward, it’s basically like an ERB view, but you’re writing JavaScript instead of Ruby.

<p>Hi there, <%= name %> <%= surname %>!</p>

This view will now be compiled and sent to the browser. If you’re using Chrome you should be able to see a file called ‘index.js’ under Resources -> Scripts in the debugging panel. This file will be a JavaScript function – basically the result of your template being compiled by EJS.

Now you can actually call this template from anywhere in your JavaScript code.

var user = { name: 'Jaco', surname: 'Pretorius' };
var result = JST['views/index'](user);

The result will be a simple HTML string for you to insert into the DOM.

As I said, I’m not saying EJS is the best solution out there, but it’s really easy to use and all the templates live on the client – no extra requests are made to the server (apart from the actual data).

Happy coding.