symbol heatxsink.com blog  ·  archive  ·  about  ·  Feed feed

Javascript Templates in jQuery

Sunday, April 25, 2010 03:32 PM

As writing web applications becomes increasingly more popular, so has the ability for an application to be "almost" completely rendered via javascript. A great example of this is Gmail. Unfortunately as a product is built it's difficult to keep from making sweeping changes in your source code. This obviously becomes painful. Especially if part of your view rendering is in javascript.

In jQuery I see alot of code like the following:

$.each(data, function(i,item) {
    $("<img/>").attr("src", item.picture_url).attr("width", "480").appendTo("#my-images").wrap("<a href='" + item.picture_page_url + "'></a>");
});

With jQuery templates it now turns into a script tag with your markup and a single line of code:

<script id="image_template" type="text/html">
    <a href="${ picture_page_url }">
        <img width="480" src="${ picture_url }" />
    </a>
</script>

...

$("#image_template").render(data).appendTo("#my-images");

You can also put your template into a string:

var template = '<a href="${ picture_page_url }"><img width="480" src="${ picture_url }" /></a>';

$("#my-images").append(template, data);

Until jquery-tmpl is included into jquery-core there's a script include up on github at http://github.com/jquery/jquery-tmpl.