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’:Next launch generator: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.handlebarsContent:You can render this partial in ActiveView:And in JavaScript:If you want use handlebars partials, here example in ActiveView:And in Javascript: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.Demo application with scroll pagination you can find hereSource code: https://github.com/le0pard/st_rails_exampleThat’s all folks!

Links

Rubygems: https://rubygems.org/gems/sht_railsSource code: https://github.com/railsware/sht_rails