Discussions

How to use Handlebars.precompile API in Javascript

There are many resources on the internet that explain how to compile Handlebars templates on the fly in Javascript, but not much explanation can be found on how to use Handlebars precompile through API (and not through CLI command-line interface).

Below is the right way of doing it.

Assuming you have your Handlebars template as string in theTemplateScript variable, the usual steps to follow to get HTML rendered from that script are:

The above presents the usual Handlebars compilation procedure. If you want to avoid compiling your templates every time and precompile them once and reuse the precompiled result, then you need to do as below:

Instead of calling Handlebars.compile() method you would need to call Handlebars.precompile() method. It returns a string that you can save to Database or file somewhere and read it back through ajax if you want later.

Once you have the precompiled string, then to get back the template object from that string you need to do some kind javascript function gimmick as below:

Note the new Function(...)() statement. It takes the string output from the Handlebars.precompile and converts it into a valid JSON object (which gets returned to you as the return value of an anonymous function, hence the return statement).