AJAX: Javascript templating for updating html with JSON response

February 9th, 2014

Updating a web page with new data from a response after an AJAX call is a very common task, but still many developers send entire html chunks in the response to the javascript, probably mostly due to laziness, while others send JSON but have prepared html in the javascript file which isn’t much better and could be a hassle to modify at a later stage.

There are a few solutions that enabled you to build a javascript template so only JSON is transmitted and the html is still easy to overview and modify. Here’s one I’ve tried out, including demo and an easy implementation guide: blueimp Javascript Templates.

An example of how the javascript template might look like:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
<script id="template-article" type="text/x-tmpl">
    <article id="article{%=o.id%}">
        <img src="{%=o.articleimage%}" alt="{%=o.title%}" />
        <a href="{%=o.articlelink%}">{%=o.title%}</a>
        <p>{%#o.articletext%}</p>
    </article>
</script>

The ajax response is easy inserted with a single line into the DOM by replacing/adding the resulting HTML which is put together with this: tmpl(“template-article”, data));


Oh, if you for some reason insist on having your html inside a javascript file, you could use Nano Templates (written by Tomasz Mazur). All the code you need is right here:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Nano Templates (Tomasz Mazur, Jacek Becela) */
function nano(template, data) {
    return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
        var keys = key.split("."), v = data[keys.shift()];
        for (var i = 0, l = keys.length; i < l; i++) v = v[keys[i]];
        return (typeof v !== "undefined" && v !== null) ? v : "";
    });
}
 
var newsHtml =
    '<div id="news{id}"> \
        <h2><a href="{newsurl}">{title}</a></h2>
     </div>';
 
myjsondata = {
    id: "123",
    newsurl: "/newspage/123",
    title: "The lion has escaped!",
}
 
$('#newslist').append(nano(newsHtml, myjsondata));

Leave a Reply