预编译胡子模板或外部加载?

时间:2011-09-02 13:34:02

标签: javascript coffeescript mustache

有一个Coffeescript包含函数会很有用,所以它可以在javascript编译时加载外部胡须模板,而不会弄乱咖啡文件。

实际上你可以在运行时加载.mustache文件,但你需要使用ajax请求调用它们,并且涉及一些性能惩罚。

我想预编译一些静态胡须模板,并将它们包含在生成的javascript函数中,该函数可以是Stitched并压缩在一个文件中。

是否有项目或脚本?

6 个答案:

答案 0 :(得分:7)

我认为这个解决方案适合你,javascript模板precompiller for mustache和其他模板引擎https://github.com/kupriyanenko/jsttojs

例如,使用命令行

jsttojs templates compiled/templates/index.js --ext mustache --watch

或使用grunt的解决方案,grunt-jsttojs

答案 1 :(得分:2)

首先,您可以使用以下内容:

<script type="text/x-mustache" id="tid...">
  ... mustache template ...
</script>

将模板包含在专用脚本块中,而不是代码中的字符串。 getElementByID() + innerHtml()将为您提供可以使用的来源。

关于一般的胡子 - 严格来说你不能编译它。每次“实例化”模板时都会解释模板。

如果你确实需要编译它们,那么考虑使用我的风筝引擎: http://code.google.com/p/kite/或任何其他可编译模板: http://jsperf.com/dom-vs-innerhtml-based-templating/99

答案 2 :(得分:2)

当然,这是我工作的地方。所有模板都放在一个html文件中,并在构建时插入到dom中。每个模板都存储在未知类型的脚本标记中,因此浏览器只会忽略它。然后你可以使用选择器来引用它们。

<script type="unknown" id="id_of_template">
  <ul>
  {{#words}}
    <li>{{.}}</li>
  {{/words}}
  </ul>
</script>

render = (template) ->
  view =
    words: [ 'hello', 'there' ]
  template = $('#' + template).html()
  html = Mustache.to_html template, view

John Resig有一篇关于技术的好文章http://ejohn.org/blog/javascript-micro-templating/

答案 3 :(得分:2)

我正在做类似的事情。我还没有尝试过,但似乎你可以使用Node.js和Mu(Node.js的Mustache构建)来做到这一点。伪JS代码......

var compiledTemplate = Mu.compile("myTemplateFile.html")
fs.writeFile("myCompiledTemplate.js", compiledTemplate.toString());

答案 4 :(得分:1)

Twitter的图书馆Hogan.js完成了这项工作。

答案 5 :(得分:-1)