手动使用预编译的车把模板

时间:2013-01-02 21:05:28

标签: handlebars.js

如何手动使用预编译的handlebars.js模板?

让我们说,我们有

source = "<p>Hello, my name is {{name}}</p>"
data = { name: "Joe" }

目前,我有

template = Handlebars.compile(source)
render: -> template(data)

源来自数据库,为了减少编译时间,我想使用编译步骤,使用Handlebars.precompile(source)预编译模板服务器端,然后使用类似的东西:

template = precompiled_template
render: -> precompiled_template(data)

precompiled_template是一个带有函数定义的字符串,因此不起作用。

另外,我发现Hanlebars.compile(source)() == Handlebars.precompile(source),但在浏览了把手的源代码后,它是编译器和运行时,我仍然不确定如何实现这一点。

2 个答案:

答案 0 :(得分:4)

如果你到现在为止找不到合适的问题,答案很简单。 Handlebars在命令行中附带一个C预编译器,如果你可以访问你的shell,你可以简单地编译每个分离的模板或将它们合并到一个文件中。

您可以通过npm /安装Handlebars,或者在您的系统上构建它。 在shell上,您可以访问帮助文件

  

$&GT;把手[ENTER]

您会看到一个类似&gt;的帮助文件   - f - 输出输出文件等等..   - m --min最小化输出

  

$&GT;把手mysupertemplate.handlebars -f compiled.js -m(“-m”if   你想缩小js文件)

在浏览器中运行Handlebars.compile是一个巨大的性能损失,因此在将文件发送到浏览器之前尝试在服务器上进行预编译是值得的。

要在浏览器中注册Handlebars模板,您必须加载它们:

var obj = {"foo":"bar"}

var template = require("./mytemplate-file.js") // require.js example
    template = template(Handlebars) // Pass Handlebars Only if the template goes mad asking for his Father

var html = Handlebars.templates[template-name](obj)

例如,如果您在“templates-file”中注册了多个模板,则可以在require之后使用

按名称访问所有模板
var html = Handlebars.templates["templateName"]({"foo":"bar"});

您可以通过在文件中注册所有知道帮助程序和/或为部分内容制作自定义帮助程序来更进一步。

*// This will be the helper in you app.js file*

Handlebars.registerHelper("mypartials", function(partialName, data) {
     var partial = Handlebars.registerPartial(partialName) || data.fn
     Handlebars.partials[partialName] = partial
})

在你的模板文件中,你可以把它......

{{#mypartial "divPartial"}}
  <div id="block"><h2>{{foo}}</h2><p>{{bar}}</p></div>  
{{/mypartial}}

{{#mypartial "formPartial"}}
  <form id="foo"><input type="text" value="{{foo}}" name="{{bar}}"></form>
{{/mypartial}}

现在您可以通过调用

来访问此文件
var html = Handlebars.partials["divPartial"]({"foo":"bar","bar":"foo"})
var formHtml = Handlebars.partials["formPartial"]({"bar":"bar","foo":"foo"})

希望这有点帮助..

答案 1 :(得分:0)

此速度测试http://jsperf.com/handlebars-compile-vs-precompile/3给出了答案。

显然,一个解决方案是eval()结果字符串,它将起作用。

代码是

var data = { name: "Greg" };
var source = "<p>Howdy, {{ name }}</p>";

eval("var templateFunction = " + Handlebars.precompile(source));
var template = Handlebars.template(templateFunction);

template(data);
=> "<p>Howdy, Greg</p>" 

当然,需要注意eval,可能存在更好的解决方案。