PastBook with Handlebar(s) Mustache!

Hello everybody, this is my first post so I wanna start with a very simple but useful tip about a very cool templating tool.

Is important to remember that jQuery is not that magical black box that is capable to do everything. It does a couples of things really well. Those are working and manipulating the DOM and working with asynchronous operations like AJAX. jQuery is perfect for that, however for other things such as structuring your code or templating you wanna take a look to different tools that remain specifically for that purpose. My favourite is Mustache, a very popular and easy to use tool. Basically it emphasizes separating logic from presentation.

It is “logic-less” because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values.

As you have seen in Pastbook we use a very original and particular template to display the time and the date (Instagram Astronomical theme) so that raises a little problem: how can I create a template with a very simple logic using Mustache? The solution is Handlebars.js !

The Handlebars Web site intro says: Mustache templates are compatible with Handlebars, so you can take a Mustache template, import it into Handlebars, and start taking advantage of the extra Handlebars features. On the other hands Handlerbars is Mustache with steroids.

One of the coolest stuff about it is the Helper! Handlebars helpers can be accessed from any context in a template. You can register a helper with the Handlebars.registerHelper method and use it whenever you want.

the template:

<div class="time-style">

the HandlebarsHelper:

Handlebars.registerHelper( 'time', function() { 
  return new Handlebars.SafeString( "<p class='hours'>date.hours</p>" ); 

then when I compile the template with handlebars the result is:

<div class="time-style">
  <p class='hours'>7</p>

To make the stuff a bit more difficult, I would create a function that converts the number in to a CSS class so I can show the sticks. For instance if I wanna convert the number 7 to sticks, my function has to return:

<div class="time-style">
  <div class="5-sticks"></div>
  <div class="2-stick"></div>

Then I add that function on my HandlebarsHelper and use it whenever I need it. The result will be:

Have a load to the Instagram Pastbook, you can see the final result:

Leave a Reply