Reputation: 5043
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?
Upvotes: 10
Views: 14082
Reputation: 374
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
Upvotes: 7
Reputation: 7356
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());
Upvotes: 2
Reputation: 3758
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/
Upvotes: 2
Reputation: 27460
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
Upvotes: 2
Reputation: 369
You can render a template string included directly in your source using Mustache.to_html(), if that helps.
Upvotes: -1