Precompiling javascript templates

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

What does precompiling javascript templates do?

I used to use simple client-side caching, which worked 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?

+4
source share
2 answers

Since Handlebars.js can have different expression / rendering logic in the template, these expressions are usually processed at runtime. For better performance and less dependency, templates can be precompiled before deployment. For example, here is a simple steering pattern:

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

And here is the precompiled 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 information about precompilation can be found here.

+5
source

The short answer is that in order for the template to be evaluated / applied, it must first be turned into a javascript function. This process is a compilation that is separate from loading or saving the raw code of the template (i.e., <div....><h1>{{var}}</h1></div> in advance.

+1
source

Source: https://habr.com/ru/post/1445476/


All Articles