Search code examples
ruby-on-railstemplatessprocketsjst

Share rails templates front and back with JST support


I would like to share js templates between front and back in a rails application for cases where the code would be duplicated.

The requirements are:

  • Either underscore (ejs) or handlebars/mustache templates. Preferably ejs because I'm already using underscore client side.
  • I'd also like to utilize the rails asset pipeline to pull these into JST object/functions so I can keep the template files separate and can get the other benefits like cacheing etc.

I've found some gems that work for one case or the other like handlebars_haml_assets, ejs, FlavourSaver etc but none that allow for all of these requirements out of the box. What is the best way to share js templates front and back and also use JST in a rails 3 app?


Solution

  • Rails 3.2 asset pipeline, out-of-the-box, supports Embedded Javascript (EJS) or Embedded CoffeeScript (Eco) templates and are made available using a JST (JavaScript templates) namespace. Just name your files appropriately:

    app/assets/templates/top_level.jst.ejs
    app/assets/templates/subdir/nested.jst.eco
    

    To use them in your javascript:

    var html = JST['top_level']({ data: 'something' });
    var html = JST['subdir/nested']({ data: 'something' });