4

看完Mustache.js 和 Handlebars.js 有什么区别?我被一个问题迷惑了:

javascript模板的预编译是什么意思?

以前我使用的是一个简单的客户端缓存,它的工作原理是这样的:

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
}

这与我的技术有什么根本不同?

4

2 回答 2

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

更多关于预编译的信息可以在这里找到

于 2012-11-12T10:15:00.390 回答
1

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

于 2012-11-12T10:24:05.057 回答