Blog by Railsware

Shared Mustache Templates for Rails 3

Hello my dear friends. Today we will talk about how we share mustache templates in Rails 3.

Let’s imagine that we have a task, where on first load of the page we show only 10 products. But when user scroll, we should automatically load more products on page (aka continuous pagination).
Of course, this task can be solved in several ways, but I want solve this task by sharing one template between Rails and JavaScript.

There are many JavaScripts templates exists today – Hogan.js, Handlebars, Mustache etc. I choose Mustache, because it’s simple and has template engine implemented on many languages (we need JavaScript and Ruby). We created a gem for such type of tasks – smt_rails.
How it works?

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

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

Next launch generator:

rails g smt_rails:install

That’s all.

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

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

Content:

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

You can render this partial in ActiveView:

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

And in JavaScript:

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

So in the end you’ll have only one template, which is shared between Rails and JavaScript.

Demo application with scroll pagination you can find here

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

That’s all folks!

SMT_rails (Shared Mustache Templates for Rails)

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

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

Exit mobile version