YUI 3: Compiling Handlebars templates using grunt-flex-handlebars

Although compiling Handlebars templates can be easy, if the templates do not follow the arbitrated convention, then it can be painful to continuously prepare the template file. I finally set some time aside to work with Grunt, and I must confess: why didn’t I start sooner? With a little bit of configuration, I was able to effortlessly compile the templates with grunt-contrib-handlebars. On top of template dynamic compilation, the Grunt watch task precompiled any templates on the fly.

Trouble with grunt-contrib-handlebars?

Precompiling templates worked brilliantly, but the options were too restrictive. The grunt-contrib-handlebars plugin offered a variety of options that accommodated external libraries such as requires.js, but a problem manifested in its inflexibility. Any new options needed an other option which means more coding. Even if options can be added to the code, an option for ever use case cannot be implemented without serious concerns for the tool’s code complexity or even relevance for the general audience.

Support for multiple libraries is necessary, else the tool may be overly rigid. How would external libraries, in this case YUI 3, be able to integrate into the grunt-contrib-plugin? YUI 3 Handlebars module offers Y.Handlebars as a method of accessing the underlying Handlebars code while supporting its asynchronous module loading.

Is there a way to increase the flexibility of the code while keeping the complexity low? Since Handlebars is a templating engine, could its API be harnessed to create the precompiled template files?

Solution with grunt-flex-handlebars?

Currently there does not exist a solution that uses Handlebars to precompile templates, so I created the 15th Handlebars grunt plugin called grunt-flex-handlebars. Hopefully, this plugin will help cover more cases, especially edge cases, so that Handlebars can proliferate as a templating engine. In any case, let’s see some code!

Customization

Each of the templates are fairly straight forward. There is very little to customize in the yui-helper, yui-partial, or yui-template files. In the yui-wrapper files, functions and variables can be made available to the yui-helper closures by inserting the code at line 2.

Last Thoughts

With this YUI 3 example, I hope that simplicity and flexibility of creating precompiled templates using Handlebars becomes apparent. This tool had extensibility as its goal, so I certainly look forward to other use cases.