预编译javascript模板

时间:2012-11-12 09:55:33

标签: javascript templates handlebars.js mustache client-side-templating

阅读What are the differences between Mustache.js and 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
}

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

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

相关问题