Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 966
Ronnie Avatar asked Sep 02 '11 13:09

Ronnie


3 Answers

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

like image 69
kupriyanenko Avatar answered Nov 10 '22 17:11

kupriyanenko


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

like image 30
c-smile Avatar answered Nov 10 '22 16:11

c-smile


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/

like image 2
sciritai Avatar answered Nov 10 '22 16:11

sciritai