Precompile mustache templates or load externally? - javascript

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'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.

Related

Node template engine, like EJS, that doesn't break the HTML template?

Wondering if there is a templating engine like EJS for NodeJS that doesn't break the original template HTML through its use of parenthesis.
In EJS, for example, one might use the following to insert specific data into the HTML template:
<script>
window.$data = <%- JSON.stringify(data, null, 4) %>;
</script>
Note that the <%- %> parenthesis breaks the source HTML file, rendering it useless for quick-fire testing in situations when your want to temporarily drop the use of the EJS parser.
Ignoring disputes of usefulness for a moment, are there any good data-injection libraries for Node which don't break the template? Or, dare I say, for the simple injection of a stringified object into a certain <script> element, would a regular expression be out-of-the-question?
As you know, EJS would break HTML with it's '<% >' , and the syntax of it looks much like ASP.
If you want a new template which not break HTML, and has a nice coding work flow, you can try this:
Github: https://github.com/eshengsky/saker
It's my personal open source project named Saker, it enables a really compact and expressive syntax which is clean, fast and fun to type.
Here's the preview:
<span>#name</span>
#title

Precompiling server-side html templates using grunt

Using Grunt I was wondering if there were some existing build process to precompile server-side templates.
Actually with usual template engines, you often use features like "include", "extend layout.html", ...
This means you could be able to just precompile your template doing all stuff that can be
"statically" solve. For example with ect and the "include" feature:
a.ect
<div>Hello I'm <%= #name %></div><% include 'b.ect' %>
b.ect
<div>I'm included in a.ect</div>
Since there is no conditional dynamic statement to decide if the b.ect block has to be included, a.ect could be statically compiled including b.ect into ./dist/a.ect:
<div>Hello I'm <%= #name %></div><div>I'm included in a.ect</div>
As you can see, ./dist/a.ect is still a template, and the #name variable stills need to be provided, so in this case, this part remains unchanged. However, the inclusion is static so it can be done right now avoiding the useless inclusion at runtime (even with a cache)
Using this approach, we could even think about minifying templates during this build process, and more. For the minifying task, I am aware of tools like htmlmin but this is oriented for valid html.
I've also found some grunt tasks (grunt-ect, grunt-contrib-jade, etc) which compiles your templates into html by providing the context. However it seems that it expects to get all the dynamic parts of your templates i.e. the value of all variables.
Any idea if this kind of precompilation tool already exists for a template engine even without grunt?
PS: This could be a bad approach, so any advice is welcome.
Probably not excactly what you are looking for,
but there's a precompiler for handlebars templates available via npm, which renders templates in one minified js file:
https://npmjs.org/package/handlebars-precompiler

Loading templates in a single file for backbone / underscore

I have a backbone application, which is served by a symfony2 server.
I have many backbone views and each has several templates that are rendered at different times using underscore's templating engine.
I am trying to figure out how to serve the underscore templates to the client with maximum efficiency.
Up until now I've written all of the templates in twig, and then rendered them as inline script tags to the response HTML during the initial request. This resulted in a long response time from the server during the first time a user enters my application.
output example:
<html>
<head>
...
</head>
<body>
<script type="text/template" id="template1">
<div class="example">
<%= someparam %>
</div>
</script>
<script type="text/template" id="template2">
<div class="anotherExample">
<%= otherparam %>
</div>
</script>
...
...
...
</body>
</html>
Alternatives
Now I'm looking for a better way to load these templates. perhaps by getting them in a second request in a single file, like an external JS file. But with anything I've tried, I have found it difficult to either access individual templates (like referencing them by id) or to keep them all in an efficient structure (in a single file, and without too much string manipulation or too many http requests).
TL;DR
How would one load many underscore templates?
You could consider the JST approach, which is to concatenate the templates into a single javascript file. The pattern is described in this Backbone Patterns tutorial.
I'm not familiar with Symfony/Twig, so I don't know if there is any tooling available. Based on your question I would guess it's easy to use your existing tools to render the templates into a javascript file instead of the HTML document.
I think better way for you - it's precompile template, try to use jsttojs, it will help you get single file with all you templates.
for example, from command line
jsttojs templates compiled/templates/index.js --ext mustache --watch
or use solution for grunt, grunt-jsttojs

How to use javascript templating rather than raw HTML in javascript string?

I am creating a web app that requires me to render new elements on the page many, many times. It is getting out of hand for me to add HTML by putting it into a Javascript string. Mostly because it's hard to edit it especially when it spans multiple ways. What's the best solution for this? And what's the best way to organize this stuff because I feel like I am going to have a huge page full of JS "subelements".
There are a huge number of JavaScript templating engines available. Some of the more popular ones include:
Mustache
Handlebars
Underscore
jQuery.template
Most work by compiling your template text into a function that can be called with an object containing the data to be interpolated.
For example (using underscore.js):
var myTemplate = _.template("Hello <%= person %>");
alert(myTemplate({person : "egidra"}));
Here is a link about linked.in and templates.
I would use a js template engine. So no need to use html strings in the js. Look at the documentation of the templates. They all explain the use very well.
You can try something like http://handlebarsjs.com/ or http://mustache.github.com/.

Explanation of <script type = "text/template"> ... </script>

I just stumbled upon something I've never seen before. In the source of Backbone.js's example TODO application (Backbone TODO Example) they had their templates inside a <script type = "text/template"></script>, which contained code that looks like something out of PHP but with JavaScript tags.
Can someone explain this to me? Is this legit?
Those script tags are a common way to implement templating functionality (like in PHP) but on the client side.
By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.
Backbone doesn't force you to use any particular templating library - there are quite a few out there: Mustache, Haml, Eco,Google Closure template, and so on (the one used in the example you linked to is underscore.js). These will use their own syntax for you to write within those script tags.
It's legit and very handy!
Try this:
<script id="hello" type="text/template">
Hello world
</script>
<script>
alert($('#hello').html());
</script>
Several Javascript templating libraries use this technique. Handlebars.js is a good example.
By setting script tag type other than text/javascript, browser will not execute the internal code of script tag. This is called micro template. This concept is widely used in Single page application(aka SPA).
<script type="text/template">I am a Micro template.
I am going to make your web page faster.</script>
For micro template, type of the script tag is text/template. It is very well explained by Jquery creator John Resig http://ejohn.org/blog/javascript-micro-templating/
To add to Box9's answer:
Backbone.js is dependent on underscore.js, which itself implements John Resig's original microtemplates.
If you decide to use Backbone.js with Rails, be sure to check out the Jammit gem. It provides a very clean way to manage asset packaging for templates.
http://documentcloud.github.com/jammit/#jst
By default Jammit also uses JResig's microtemplates, but it also allows you to replace the templating engine.
It's a way of adding text to HTML without it being rendered or normalized.
It's no different than adding it like:
<textarea style="display:none"><span>{{name}}</span></textarea>
<script type = “text/template”> … </script> is obsolete. Use <template> tag instead.
jQuery Templates is an example of something that uses this method to store HTML that will not be rendered directly (that’s the whole point) inside other HTML:
http://api.jquery.com/jQuery.template/

Categories

Resources