Hoganizer: Precompile mustache templates for the frontend

Posted at September 14, 2013

Normally when I start working on a new webapp I end up using Jade as a template language, to get the templates working on the frontend I use a wonderful tool called templatizer which pre compiles all jade templates into plain javascript functions. I love this workflow because it has some awesome advantages like:

  • Insanely fast rendering, because you are just running vanillaJS functions with strings in them.
  • You still get to write your templates in a very friendly format: a .jade file for each template.
  • The compiled templates are stored in .js files, which means you have a lot of control over the client side caching.
  • The whole template parsing engine doesn’t need to go over the wire, this way your total JS size goes down.

But this time I started a new project and we decided to go for mustache instead of jade. After some searching I came across Twitter’s fast implementation of the mustache spec: hogan.js. The library not only promises to be very fast, but also that it consists of different modules that would make it easy to pre compile templates on the server.

There already were some wrappers available, but none fit quite right into my workflow: it must be easy to hook into my buildscript & must have some way of supporting client side development.

Meet Hoganizer, a small wrapper around the Hogan compiler to make this easier.

Install

npm install hoganizer

Usage example

var Hoganizer = require('hoganizer');
var hoganizer = new Hoganizer({
    templateDir: './templates',
    extension: '.mustache',
    writeLocation: './templates.js'
});

// Compile all mustache templates in `./templates` and write
// them into frontend js file to `./templates.js`.
hoganizer.write();

// Compile but save the script as a string
var vanillaJS = hoganizer.precompile();

// Grab the latest compiled version
var vanillaJS = hoganizer.getCached();

Check it out on Github.