Tuesday, May 8, 2012

Precompiling handlerbars tempates with Rhino.js

Handlebars is awesome templating engine, which can be compiled to html by a javascript engine.

With handlebars, it is also possible to precompile your templates and it results in a smaller required runtime library and significant savings from not having to compile the template in the browser. This can be especially important when working with mobile devices.

Handlebars provides precompiler script with node.js. But for some reason, if you cannot have node.js in your development box or if you already have Rhino as part of your stack, you dont have to introduce node.js just for this. 

I came up with this port of handlebars precompiler with Rhino. You can get it at https://gist.github.com/2629244.

And its usage is: java -jar rhino-handlebars-compiler.js --handlebars --templates --output

and here is a sample ant task to trigger it as part of your build process.

<?xml version="1.0"?>
<target name="precompile-templates">
  <java dir="${basedir}" jar="lib/rhino-js.jar" fork="true" failonerror="true">
    <arg value="web/js/lib/rhino-handlebars-compiler.js"/>
    <arg value="--handlebars"/>
    <arg value="web/js/third-party/handlebars.min.js"/>
    <arg value="--templates"/>
    <arg value="web/templates/"/>
    <arg value="--output"/>
    <arg value="web/js/compiled-templates.js"/>
  <echo>Template Precompiled to web/js/compiled-templates.js</echo>


Unknown said...

You rock, man! Thanks for this post.

I got it to work with maven:

Added this dependency:

Then this plugin to my build:


Unknown said...

Awesome, thank you!

Vibha Joshi said...

Does it only work if the template extension is .handlebars? I have templates with the extension ".html" but it does not work for me

venkat said...

Good post thanks.