简体   繁体   中英

Precompile mustache templates or load externally?

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 project 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的图书馆Hogan.js完成了这项工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM