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:

  var theTemplateScript = "Welcome {{name}}, {{species}} from {{planet}} !!";

  // Compile the template directly as below
  var theTemplate = Handlebars.compile(theTemplateScript);

  // Pass your data to the template
  var theCompiledHtml = theTemplate(data);

  // Add the compiled html to the page
  $('.content-placeholder').html(theCompiledHtml); 

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:

  var precompiled = new Function("return " + Handlebars.precompile(theTemplateScript))();  
  var theTemplate = Handlebars.template(precompiled);

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

The full code then becomes:

   // your data object
  var data = {
    "name": "John",
    "species": "Earthling",
    "planet": "P-221GX E1-03"
  };

  // load your handlebars template script from ajax / DOM
  var theTemplateScript = "Welcome {{name}}, {{species}} from {{planet}} !!";

  // precompile your handlebars script
  var precompiled = new Function("return " + Handlebars.precompile(theTemplateScript))();  
  var theTemplate = Handlebars.template(precompiled);

  // Pass your data to the template
  var theCompiledHtml = theTemplate(data);

  // Add the compiled html to the page
  $('.content-placeholder').html(theCompiledHtml); 

You can try the above script on a sample html page that contains below line:

<html> <div class="content-placeholder"></div> </html>

Comments