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:

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' });