# 预编译模板

¥Precompiling templates

使用 Handlebars 预编译器,你可以预编译 Handlebars 模板,以节省客户端时间并减少 Handlebars 库所需的运行时大小。

¥Using the Handlebars precompiler, you can precompile your Handlebars templates to save time on the client and reduce the required runtime size of the handlebars library.

# 入门

¥Getting started

首先,你需要有 Node.js 和 npm。请转至 https://nodejs.cn/download/ (opens new window) 了解如何在你的操作系统上执行此操作。

¥First, you will need to have Node.js and npm. Go to https://nodejs.cn/download/ (opens new window) to find out how to do that on your OS.

接下来,安装 Handlebars npm 包,其中包含预编译器。

¥Next, install the Handlebars npm package, which contains the precompiler.

npm install -g handlebars

创建包含你的模板的文件名 example.handlebars

¥Create a file name example.handlebars containing your template:

Handlebars <b>{{doesWhat}}</b> precompiled!

运行预编译器。

¥Run the precompiler.

handlebars example.handlebars -f example.precompiled.js

包括 Handlebars 运行时和预编译 javascript。

¥Include the Handlebars runtime and the precompile javascript.

<div id="output"></div>
<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.runtime.js"></script>
<script src="example.precompiled.js"></script>
<script>
  var template = Handlebars.templates.example;
  document.getElementById('output').innerHTML = template({doesWhat: 'rocks!'})
</script>

该运行时也可以在 安装页面 上下载。

¥The runtime is also available for download on the installation page.

# 优化

¥Optimizations

由于你正在预编译模板,因此你还可以对编译器应用多种优化。第一个允许你向编译器指定已知辅助程序的列表

¥Because you are precompiling templates, you can also apply several optimization to the compiler. The first allows you to specify a list of the known helpers to the compiler

handlebars <input> -f <output> -k each -k if -k unless

Handlebars 编译器将优化对这些助手的访问以提高性能。当所有辅助程序在编译时已知时,--knownOnly 选项提供最小的生成代码,同时也提供最快的执行。

¥The Handlebars compiler will optimize accesses to those helpers for performance. When all helpers are known at compile time, the --knownOnly option provides the smallest generated code that also provides the fastest execution.

# 用法

¥Usage

Precompile handlebar templates.
Usage: handlebars [template|directory]...
Options:
  -f, --output         Output File                                                                              [string]
  --map                Source Map File                                                                          [string]
  -a, --amd            Exports amd style (require.js)                                                          [boolean]
  -c, --commonjs       Exports CommonJS style, path to Handlebars module                        [string] [default: null]
  -h, --handlebarPath  Path to handlebar.js (only valid for amd-style)                            [string] [default: ""]
  -k, --known          Known helpers                                                                            [string]
  -o, --knownOnly      Known helpers only                                                                      [boolean]
  -m, --min            Minimize output                                                                         [boolean]
  -n, --namespace      Template namespace                                     [string] [default: "Handlebars.templates"]
  -s, --simple         Output template function only.                                                          [boolean]
  -N, --name           Name of passed string templates. Optional if running in a simple mode. Required when operating on
                       multiple templates.                                                                      [string]
  -i, --string         Generates a template from the passed CLI argument.
                       "-" is treated as a special value and causes stdin to be read for the template value.    [string]
  -r, --root           Template root. Base value that will be stripped from template names.                     [string]
  -p, --partial        Compiling a partial template                                                            [boolean]
  -d, --data           Include data when compiling                                                             [boolean]
  -e, --extension      Template extension.                                              [string] [default: "handlebars"]
  -b, --bom            Removes the BOM (Byte Order Mark) from the beginning of the templates.                  [boolean]
  -v, --version        Prints the current compiler version                                                     [boolean]
  --help               Outputs this message                                                                    [boolean]

如果使用预编译器的正常模式,生成的模板将使用不带扩展名的相对模板名称存储到 Handlebars.templates 对象中。这些模板可以以与模板相同的方式执行。如果使用简单模式,预编译器将生成单个 javascript 方法。要执行此方法,必须将其传递给 Handlebars.template() 方法,并且生成的对象可以正常使用。

¥If using the precompiler's normal mode, the resulting templates will be stored to the Handlebars.templates object using the relative template name sans the extension. These templates may be executed in the same manner as templates. If using the simple mode the precompiler will generate a single javascript method. To execute this method it must be passed to the Handlebars.template() method and the resulting object may be used as normal.

# 在 NodeJS 中预编译模板

¥Precompiling Templates Inside NodeJS

如果你希望从 NodeJS 内部预编译模板(而不从命令行调用 "handlebars"),可以使用 Handlebars.precompile 来完成。将此函数的字符串结果传输给你的客户端,然后他们可以使用 Handlebars.template 解析该结果。

¥If you wish to precompile templates from inside NodeJS--without invoking "handlebars" from the command line--that can be done with Handlebars.precompile. Transmit the string result of this function to your clients, and they can in turn parse that with Handlebars.template.

let template = "Handlebars <b>{{doesWhat}}</b> precompiled!";
let Handlebars = require("handlebars");
let compiled = Handlebars.precompile(template);
console.log(compiled);

输出如下:

¥The output will be the following:

{"compiler":[8,">= 4.3.0"],"main":function(container,depth0,helpers,partials,data) {
    var helper, alias1=container.propertyIsEnumerable;

  return "Handlebars <b>"
    + container.escapeExpression(((helper = (helper = helpers.doesWhat || (depth0 != null ? depth0.doesWhat : depth0)) != null ? helper : container.hooks.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"doesWhat","hash":{},"data":data}) : helper)))
    + "</b> precompiled!";
},"useData":true}

在客户端,你有如下所示的 Javascript。

¥On the client side you have Javascript along the lines of the following.

Handlebars.partials["test1"] = Handlebars.template({
  /** insert compiled output here **/
});

最后,你可以在 Javascript 中动态引用这些模板。

¥Finally, you can reference these templates dynamically in your Javascript.

var result = Handlebars.partials["test1"]({ name: "yourname" });
// do whatever you want with the result

# 集成

¥Integrations

一些 npm-packages 可用于将 Handlebars 预编译器集成到你的构建系统中(即 Webpack、Browserify...)。看一下集成页面:

¥Some npm-packages can be used to integrate the Handlebars precompiler into your build system (i.e. Webpack, Browserify...). Have a look at the integrations page:

了解更多:集成

¥!buttonLearn more: Integrations

Last Updated: 2024/3/9 17:51:41