回答

5

由于Handlebars.js在模板中可以具有不同的表达/渲染逻辑,因此这些表达式通常在运行时期间进行处理。为了获得更好的性能和更小的依赖性,可以在部署之前预先编译模板。例如,下面是一个简单的车把模板:

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

这里是预编译的输出

(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;}); 
})(); 

有关预编译的更多信息,可以发现here

1

简短的回答是对于要评估/应用的模板,必须首先将其转换为JavaScript函数。该过程是编译过程,它与下载或存储原始模板代码分开(即,提前<div....><h1>{{var}}</h1></div>