有一个 Coffeescript 包含函数会很有用,这样它可以在用 javascript 编译时加载外部 mustache 模板,而不会使咖啡文件混乱。
实际上,您可以在运行时加载 .mustache 文件,但您需要使用 ajax 请求调用它们,并涉及一些性能损失。
我想预编译一些静态胡子模板并将它们包含在生成的 javascript 函数中,该函数可以缝合并压缩在单个文件中。
有项目或脚本吗?
有一个 Coffeescript 包含函数会很有用,这样它可以在用 javascript 编译时加载外部 mustache 模板,而不会使咖啡文件混乱。
实际上,您可以在运行时加载 .mustache 文件,但您需要使用 ajax 请求调用它们,并涉及一些性能损失。
我想预编译一些静态胡子模板并将它们包含在生成的 javascript 函数中,该函数可以缝合并压缩在单个文件中。
有项目或脚本吗?
我认为这个解决方案适合你,用于 mustache 和其他模板引擎的 javascript 模板预编译器https://github.com/kupriyanenko/jsttojs
例如,与命令行一起使用
jsttojs templates compiled/templates/index.js --ext mustache --watch
或使用 grunt、grunt-jsttojs 的解决方案
首先你可以使用这样的东西:
<script type="text/x-mustache" id="tid...">
... mustache template ...
</script>
将您的模板包含在专用脚本块中,而不是作为代码中的字符串。
getElementByID()
+innerHtml()
将为您提供可以使用的来源。
关于一般的胡子 - 严格来说你不能编译它。每次您“实例化”模板时,都会对模板进行解释。
如果您确实需要编译它们,请考虑使用我的 Kite 引擎: http ://code.google.com/p/kite/或任何其他可编译模板:http: //jsperf.com/dom-vs-innerhtml-based -模板/99
当然,这是我们在我工作的地方所做的事情。所有模板都放在一个 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/
我正在考虑做类似的事情。我还没有尝试过,但您似乎可以使用 Node.js 和Mu(Node.js 的 Mustache 构建)来执行此操作。伪JS代码...
var compiledTemplate = Mu.compile("myTemplateFile.html")
fs.writeFile("myCompiledTemplate.js", compiledTemplate.toString());
Twitter 的库Hogan.js完成了这项工作。
如果有帮助,您可以使用 Mustache.to_html() 呈现直接包含在源中的模板字符串。