handlebar.js和handlebar.runtime.js有什么区别?

sta*_*tic 51 javascript templates handlebars.js

我发现handlebar.runtime.js没有compile方法.所以我下载了不正确的版本才能使用模板引擎.

但这handlebar.runtime.js是为了什么?

Download: runtime-1.0.0在下载页面上更难以察觉的更好吗?

res*_*ive 61

Handlebars使用看起来像{{this}}的标签,浏览器无法理解这些标签.为了使浏览器呈现这些标记,必须对它们进行编译.编译可以在加载页面之前或之后进行.

为了加快速度,您可以预编译模板.车把现场的更多信息.如果执行此操作,则只需在页面上包含把手运行时脚本.它比完整的手柄脚本小,因为它不需要担心编译模板.它假设您已预编译它们.

当编译模板时,它被转换为一个函数,当被调用时,它将返回真正的HTML,其中大括号标签已被转换为浏览器理解的值.

例如,这......

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

...在预编译后将转换为以下(截至2014年6月):

(function() {
  var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['test.hbs'] = template({"compiler":[5,">= 2.0.0"],"main":function(depth0,helpers,partials,data) {
  var helper, functionType="function", escapeExpression=this.escapeExpression;
  return "<div class=\"entry\">\n  <h1>"
    + escapeExpression(((helper = helpers.title || (depth0 && depth0.title)),(typeof helper === functionType ? helper.call(depth0, {"name":"title","hash":{},"data":data}) : helper)))
    + "</h1>\n  <div class=\"body\">\n    "
    + escapeExpression(((helper = helpers.body || (depth0 && depth0.body)),(typeof helper === functionType ? helper.call(depth0, {"name":"body","hash":{},"data":data}) : helper)))
    + "\n  </div>\n</div>\n";
},"useData":true});
})();
Run Code Online (Sandbox Code Playgroud)

这里重要的一点是,在某些时候,必须将把手模板转换为此功能,以便生成真正的HTML.把手运行时脚本不包含编译器,因此使其更小.通过预编译模板,JavaScript在呈现页面之前必须经历一个不那么重的步骤.

  • 我认为这是错误的。据我了解,Handlebars 编译步骤不会将模板转换为 HTML,而是为每个模板创建一个函数,该函数将存储在“Handlebars.templates”中。然后你可以将数据传递给这个函数来获取HTML,这是渲染步骤,而不是编译步骤。 (2认同)