I'm Co-Founder & CTO of BlockAvenue. , connect with me, or subscribe.

Embedding Backbone Templates in Rails with CoffeeScript

Multiline string support in CoffeeScript offers a great way to embed your Backbone templates. In this approach, you can easily edit your templates while still taking advantage of JS minification, combination, and client-side caching.

Registering and caching templates

We’ll create a top-level object in our namespace to hold our templates which are cached for efficient use across many view instances.

Using the templates

An example of using the template in a Backbone view:

In this case I’m registering and caching our templates on load. If we had more templates, or they were used less often, we could register them to be compiled on-demand which might be more efficient.