Question

After reading What are the differences between Mustache.js and Handlebars.js? I was puzzled with a question:

What does pre-compiling of javascript templates means?

Previously I was using a simple client-side caching, which was working something like this:

var tmpCache = {};
if (tmpIneed is in tmpCache){
  use it
} else {
  take it from DOM / upload from external file
  put save it in tmpCache
  use it
}

How is this fundamentally different from my technique?

Was it helpful?

Solution

Since Handlebars.js can have different expression/rendering logic in the template, these expressions are typically processed during runtime. For better performance and smaller dependency, the templates can be pre-compiled before deployment. For example, here is a simple handlebar template:

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

And here is the pre-compiled output

(function() {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['test.handlebar'] = template(function (Handlebars,depth0,helpers,partials,data) {
helpers = helpers || Handlebars.helpers;
var buffer = "", stack1, foundHelper, functionType="function",   escapeExpression=this.escapeExpression;


buffer += "<div class=\"entry\">\r\n  <h1>";
foundHelper = helpers.title;
if (foundHelper) { stack1 = foundHelper.call(depth0, {hash:{}}); }
else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1() : stack1; }
buffer += escapeExpression(stack1) + "</h1>\r\n <div class=\"body\">\r\n    ";
foundHelper = helpers.body;
if (foundHelper) { stack1 = foundHelper.call(depth0, {hash:{}}); }
else { stack1 = depth0.body; stack1 = typeof stack1 === functionType ? stack1() : stack1; }
buffer += escapeExpression(stack1) + "\r\n  </div>\r\n</div>";
return buffer;});
})();

More info about pre-compiling can be found here

OTHER TIPS

The short answer is that, for the template to be evaluated/applied, it has to be turned into a javascript function first. That process is compilation, which is separate from downloading or storing the raw template code (i.e. the <div....><h1>{{var}}</h1></div> in advance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top