Read more

Compiling Javascript template functions with the asset pipeline

Henning Koch
September 16, 2013Software engineer at makandra GmbH

The asset pipeline (which is actually backed by sprockets Show archive.org snapshot ) has a nice feature where templates ending in .jst are compiled into Javascript template functions. These templates can be rendered by calling JST['path/to/template'](template: 'variables'):

<!-- templates/hello.jst.ejs -->
<div>Hello, <span><%= name %></span>!</div>

// application.js
//= require templates/hello
$("#hello").html(JST["templates/hello"]({ name: "Sam" }));
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

Whatever is in the <% ... %> is evaluated in Javascript. You can also use CoffeeScript here:

Sprockets supports two JavaScript template languages: EJS, for embedded JavaScript, and Eco, for embedded CoffeeScript. Both languages use the familiar <% … %> syntax for embedding logic in templates.

This allows you to e. g. write templates for Backbone views using Haml.

Posted by Henning Koch to makandra dev (2013-09-16 08:23)