开发者

Precompile mustache templates or load externally?

开发者 https://www.devze.com 2023-04-02 14:52 出处:网络
It would be useful to have a Coffeescript include function so it could load the external mustache templates when compiling in javascript and not clutter the coffee files.

It would be useful to have a Coffeescript include function so it could load the external mustache templates when compiling in javascript and not clutter the coffee files.

Actually you can load .mustache files at runtime but you need to call them with an ajax request with some performance penalities involved.

I would like to precompile some static mustache templates and include them in generated javascript function that could be Stitched and compressed in a single file.

Is there a p开发者_JAVA技巧roject or a script for that?


I think this solution for you, javascript template precompiller for mustache and othe template engines https://github.com/kupriyanenko/jsttojs

for example, use with command line

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

or use solution for grunt, grunt-jsttojs


First of all you can use something like this:

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

to include your templates in dedicated script blocks rather than as strings in code. getElementByID() + innerHtml() will give you its source that you can use.

About the Mustache in general - you cannot compile it strictly speaking. Templates get interpreted each time you "instantiate" the template.

If you do need to compile them then consider use of my Kite engine: http://code.google.com/p/kite/ or any other compileable templates: http://jsperf.com/dom-vs-innerhtml-based-templating/99


Absolutely, this is something we do where I work. All the templates go in a single html file and get's inserted into the dom at build time. Each template is stored in a script tag of type unknown so the browser just ignores it. Then you can reference them using selectors.

<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 has a good article on the technique http://ejohn.org/blog/javascript-micro-templating/


I'm looking at doing something similar. I haven't tried this yet, but it seems like you could use Node.js and Mu, the Mustache build for Node.js, to do this. Pseudo-JS code...

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


Twitter's library Hogan.js does the job.


You can render a template string included directly in your source using Mustache.to_html(), if that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消