Home > Code Hints, Engineering, HOW TO, Technology > HOW TO: Better JavaScript Templates

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.

Better JavaScript Templates

Categories: Code Hints, Engineering, HOW TO, Technology Tags:
  1. jianwu
    March 6th, 2008 at 01:26 | #1

    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.

  2. xor
    March 6th, 2008 at 10:00 | #2
  3. May 2nd, 2010 at 08:55 | #3

    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:{}

  4. May 2nd, 2010 at 08:58 | #4

    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.

  1. March 5th, 2008 at 14:54 | #1

Switch to our mobile site