123

Shared Handlebars Templates for Rails 3

| 2 Comments

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.handlebars

Content:

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 here

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

Share
* Railsware is a premium software development consulting company, focused on delivering great web and mobile applications. Learn more about us.
  • Bvsat

    If I have a BigDecimal as one of the values in the hash being rendered by rails, it is crashing the ruby interpreter. I am using 1.9.3 version of Ruby and 3.2.6 version of rails. I don’t have that problem when using mustache

  • http://www.arrogantgamer.com/ arrogant.gamer

    Nice gem!

Want to get more of Railsware blog?

RSS FEED

We're always ready to help!

CONTACT US