Opinion: Mustache vs Handlebars
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I was curious about your experience/opinion using Mustache or Handlebars specifically in a Rails environment. Which one did you find had easier syntax to grasp?

awarded to alixaxel

Crowdsource coding tasks.

1 Solution

Winning solution

Not from a Rails background, but this applies everywhere:

  • Handlebars is an extension to Mustache, yet they use the same root logic-less syntax: {{variable}}.
  • Handlebars supports custom (and ships with a few useful built-in) helpers and paths (like in JSON).
  • Handlebars compiles templates to Javascript code, making the variable interpolation / rendering faster.

They are both designed to live and render client-side templates, however, since Mustache has been around for longer, there are several server-side template engines for it in nearly all the web-oriented languages. Some languages also have libraries for server-side Handlebars rendering, but they are just not as mature.

Bottom line is, if you're not rendering on the client-side, your choice is Mustache (or ERB / other).

If you're rendering on the client-side then you have two good options:

  • Hogan.js - just like bare Mustache.js, but faster as it also supports compiling templates
  • Handlebars.js - for the neat features, also faster than bare Mustache, but about half the speed of Hogan

Client side rendering has two main benefits IMO:

  • lower content to send over the wire (you just grab the JSON data and not the whole HTML markup)
  • no need to concatenate ugly HTML on client side, with jQuery or any other DOM method

Here's a benchmark comparing the three and here is another good breakdown.

Actually there's no much need to add Rails specific stuff to use Mustache/Handlebars templates. You can just generate JSON data in the Rails backend and feed it to the templates. I'm not gonna provide a separate solution since I've never wrote anything serious with Rails + Mustache/Handlebars templates but I can point to some great tutorials for using Rails as an API with a javascript frontend (Angular.js, Ember.js, etc): http://rockyj.in/2013/10/24/angular_rails.html, http://railscasts.com/episodes/408-ember-part-1)
kc00l over 5 years ago