HOW TO: Better JavaScript Templates
JavaScript Templates (Jst) is a pure Javascript templating engine that runs in your browser using JSP-like syntax. If that doesn’t sound familiar, check out the live working example on this site and download the code. It’s Free Open Source Software.
Categories: Code Hints, Engineering, HOW TO, Technology
Good Idea. I have done the similar thing, but replaced <% with some other tags as it will confuse the server side JSP engine.
This is definately very important for AJAX development, as AJAX usually transfer data from server, we need a template engine to render the data for presentation to avoid mix the template logic inside the javascript code. JSP template provides a very clean seperation, at the same time, it still proivdes full power of a programming language.
I found it’s much simpler to implement this kind of engine compare to using java language as javascript is a dynamic language which provides a handy “eval()” method.
Maybe this is of an interest: http://synodinos.wordpress.com/2008/02/22/the-way-of-client-side-templating/
Works great! I use it in combination with Jquery and added the option to download and cache the templates:
In the evaluate function:
// check if template already loaded before
if(Jst.templates[src] != true)
{
// load the template synchronous
$.ajaxSetup({async:false});
$.get(Jst.templateRoot + src +’.jst.html’, function(data)
{
// create the textarea container and add the loaded template
$(”body”).append(”+ data +”);
// update the templates status array
Jst.templates[src] = true;
});
// set the global ajax setup back to asynchronous
$.ajaxSetup({async:true});
}
// parse the data with the template
var script = Jst.parse($(”#jst_”+ src).text());
eval(script);
Extra helper var’s:
// the folder where the templates are located
templateRoot:”",
// status array keeping track if templates were loaded before
templates:{}
hmm, the textarea html tag was stripped when posting the comment above. it should be between the quotes in the append call. let me know if you whant the whole source.