Shared Handlebars Templates for Rails 3

Hello my dear friends. Today we will talk about the way, how we share handlebars templates in Rails 3. In the previous article I explained you how we share mustache templates between rails backend and javascript frontend in our company. After article publication, many people turned to the question “What about handlebars templates?”. With a little of efforts, we have created an alternative gem for shared templates – SHT_rails (Shared Handlebars Templates for Rails).

How it works?

First of all you have to add this gem to your Gemfile and start ‘bundle install’:

gem 'sht_rails', git: 'git://github.com/railsware/sht_rails.git'

Next launch generator:

rails g sht_rails:install

That’s all.

Now you can create a directory in ‘app/templates’ handlebars templates (these templates ends with ‘.handlebars’ by default). Let’s create partial for the product:

File: ‘app/templates/products/_product.handlebars

Content:

<a href="{{url}}">{{title}}</a>
<p>{{description}}</p>

You can render this partial in ActiveView:

<%= render "products/product", :handlebars => product.as_json %> 

And in JavaScript:

var product = … ; come from ajax call as json
var content = SHT['products/product'](product);

If you want use handlebars partials, here example in ActiveView:

<%= render "products/product", :handlebars => product.as_json, :partials => {:partial_key => (render "products/partial")} %>

And in Javascript:

Handlebars.registerPartial('partial_key', SHT['products/partial'])
content = SHT['products/product'](product)

So in the end you’ll have only one template, which is shared between Rails and JavaScript. The gem has one disadvantage (in my humble opinion) – it installed on the backend “therubyracer” gem, which compile templates on backend. Basically this gem is used to precompile assets in rails and doesn’t require on production.

Source code: https://github.com/le0pard/st_rails_example

That’s all folks!

Links

Rubygems: https://rubygems.org/gems/sht_rails

Source code: https://github.com/railsware/sht_rails