正如Jade所做的那样,正确预编译Handlebars模板的方法

时间:2013-03-17 08:10:00

标签: javascript node.js handlebars.js

简而言之,我需要 - 以编程方式(而不是CLI)将手柄模板预编译到浏览器端功能,并在浏览器中以这种方式将其与handlebars.runtime.js一起使用:

html = template_as_fn(data_object);

为什么我需要它 - 我在YA ComonJS上使用浏览器打包工具clinch,我也想支持Handlebars。

所以,我正在寻找正确的方法来预编译Handlebars模板,而没有eval()和其他伏都教魔法。

answer

中的内容
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>"
让我难过。

例如,对于Jade,我可以这样使用file processor

'.jade'   : (data, filename, cb) ->
  content = Jade.compile data, _.assign jade_settings, {filename}
  cb null, "module.exports = #{content}"

是否可以做一些像Jade with Handlebars?

1 个答案:

答案 0 :(得分:1)

哦,没关系!我找到了。

Handlebars的文件处理器

'.handlebars', (data, filename, cb) ->
  content = Handlebars.precompile data
  cb null, "module.exports = #{content}"

在模块两步解决方法中:

renderData : (data) ->
  template_fn = require './template' # /template.handlebars
  template = Handlebars.template template_fn

  res = template data

所以,从现在起clinch将支持Handlebars:)