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"/>
  </java>
  <echo>Template Precompiled to web/js/compiled-templates.js</echo>
</target>

4 comments:

Luis said...

<dependency>
<groupId>org.mozilla</groupId>
You rock, man! Thanks for this post.


I got it to work with maven:

Added this dependency:
<artifactId>rhino</artifactId>
<version>1.7R3</version>
<scope>compile</scope>
</dependency>



Then this plugin to my build:


<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>org.mozilla.javascript.tools.shell.Main</mainClass>
<classpathScope>compile</classpathScope>
<arguments>
<argument>src/main/webapp/js/rhino-handlebars-precompiler.js</argument>
<argument>--handlebars</argument>
<argument>src/main/webapp/js/handlebars-1.0.0.beta.6.js</argument>
<argument>--templates</argument>
<argument>src/main/webapp/js/templates/</argument>
<argument>--output</argument>
<argument>src/main/webapp/js/compiled-templates.js</argument>
</arguments>
</configuration>
</plugin>

Hamed Asghari said...

Awesome, thank you!

Gautam 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.