JsErb - Javascript renderer for Ruby on Rails
Today’s projects contain more and more javascript code. Thus, from the design perspective, javascript should be located under the RAILS/app directory instead of RAILS/public. Javascript usually produces at least a small piece of HTML code thus the Javascript templating is needed. Sites also require translations. Finally there are cases when you really need to put some ruby code into javascript. These are the features of the JsErb plugin.
Installation (Rails 3 ready)
Add this line to your Gemfile
gem 'js_erb'
Move public/javascripts directory to app/javascripts. Files with *.jserb extension can contain ERB-styled ruby code (e.g. <%= var %>).
Create a RAILS/config/locales/en.js.yml file
# Javascript translations
en:
welcome: 'Welcome'
Create a configuration file RAILS/config/js_erb.yml
# Source paths
path:
views: app/views
source: app/javascripts
compiled: public/javascripts/compiled
locales: config/locales
# List of Haml, ERB or HTML files (base on path.source path)
views:
- users/_user.html.haml
- users/_line.html.erb
You have to change the views list of the configuration file. Note also you can use ruby code inside the yml file (e.g. <%= var %>).
At the end set javascript_include_tag (add javascript files into the <head>).
Javascript HTML Templates & Translations
JsErb will, in addition to javascript source files, create a javascript file with translations and javascript file with HTML templates. You can access them anywhere in your javascript like
# Access transations
alert( i18n.t('welcome') );
# Access template
alert( jserb.v('users.user') );
JsErb With Jammit
Best practice is to use a packager to optimize project’s javascript and stylesheets. You can easily connect JsErb plugin with Jammit assets packager. To integrate JsErb with Jammit you simply define JsErb’s generated compiled files (at RAILS/public/javascripts/compiled) in to Jammit’s assets.yml file.
JsErb Caching
The plugin will always compile files in the development or testing environment. In other environments (e.g. production) it will compile files only if the compiled directory is not present.