Oct 18, 2011

Eco Templates in Rails 3.1 Asset Pipeline

CoffeeScript is supported by default in the Rails 3.1 asset pipeline, so you would suppose that support for the Eco library for embedded CoffeeScript templates would be included as well. I did anyway, and was surprised when Rails 3.1.1 treated my new .eco file as a foreigner:

ActionView::Template::Error (no such file to load -- eco


How do I get Rails 3.1 to package my Eco templates?



Add the following line to your Gemfile:

gem 'eco'

Run bundle install and Sprockets (a.k.a. the asset pipeline) is now ready to compile .eco files in app/assets/javascripts to JavaScript.


How do I find and render my Eco templates in my CoffeeScript?



Let's assume you want your embedded template to live in:

app/assets/javascripts/todos/views

If you think you can name your template todo.eco or even todo.js.eco, you're wrong. (Todos is an archetypical JavaScript framework demo app.) Although the template compiles down to a JavaScript function, at the time of this writing, the JavaScript compiled from todo.js.eco will produce a runtime error. Apparently, a JavaScript templating system is required. The easiest solution is to use JST, which Sprockets provides by default. (jQuery Templates are another option, via the sprockets-jquery-tmpl gem.)

Thus,

app/assets/javascripts/todos/views/todo.jst.eco

can be rendered in your CoffeeScript using:

JST['todos/views/todo']()

For a full working example of Eco templates with Rails and Spine, check out Alex MacCaw's infinite scrolling screencast and source.

Update (12/14/2011): Slides from my presentation on Eco at URUG are now online: http://backbonecoffeescript.com/eco-coffeescript-templates

6 comments:

  1. In your slides, you had said "It’s up to you to prepare your context, but once you do, help is at hand.". Can you give an example of how to wire up context helpers?

    ReplyDelete
  2. Ken, the short answer is that with Eco, it's up to you to do it in ad-hoc fashion. Just include any helper functions you want as properties on the "context" object you pass in when rendering. Check back here again in a couple days, I will put up an interactive Try Eco page illustrating this.

    ReplyDelete
  3. Ken,

    I wrote a short tutorial about context and helpers in Eco:

    http://backbonecoffeescript.com/eco-helpers-tutorial

    ReplyDelete
  4. Just a quick note -- the JST var won't be defined (you'll get a "Uncaught ReferenceError: JST is not defined") unless you 'require' your templates like any other javascript file (eg, in application.js, //=require todos/views/todo).

    This includes the compiled eco template in the rest of your assets, defining JST['todo']. (Somehow I missed this -- I guess I thought it would just be magic?)

    Thanks for the writeup, helped a lot.

    ReplyDelete
  5. Has anyone used these with requirejs or requirejs-rails?

    ReplyDelete
  6. This is what I was looking for, thanks :D

    ReplyDelete