JavaScript Templating Options

Javascript templating is a technique to render JSON data in HTML markup with JavaScript.

Handlebars is a semantic web template system, started by Yehuda Katz in 2010. Handlebars.js is a superset of Mustache, and can render Mustache templates in addition to Handlebars templates.

Handlebars

The document body will need an element that the template will be injected into. Since the template in this example will be a list item for each artist, an unordered list element is the logical choice.

Template Target
<!-- template wrapper -->
<ul class="artist-list"></ul>
Template Source
<!-- template -->
<script id="tmpl-artist" type="text/tmpl">
    {{#each this}}
    <li data-artist-id="{{ArtistId}}">{{Name}}</li>
    {{/each}}
</script>
JavaScript
//jQuery and Handlebars
$(function() {
    var tmplSource = $('#tmpl-artist').html(),
        template = Handlebars.compile(tmplSource);

    $.getJSON('//jimfrenette.com/api/chinook/artists').done(function(data) {
        if (data) {

            $(".artist-list").html(template(data));
        }
    });
});

A utility library delivering consistency, customization, performance, and extras.

Template Target (same as above)
Template Source
<!-- template -->
<script id="tmpl-artist" type="text/tmpl">
    <% _.forEach(data,function(artist) { %>
    <li data-artist-id="<%= artist.ArtistId %>"><%= artist.Name %></li>
    <% }); %>
</script>
JavaScript
//jQuery and Lo-Dash
$(function() {
    var tmplSource = $('#tmpl-artist').html(),
        template;

    $.getJSON('//jimfrenette.com/api/chinook/artists').done(function(data) {
        if (data) {

            template = _.template(tmplSource)({
                data: data
            });

            $(".artist-list").html(template);
        }
    });
});

jQuery only templates

A jQuery only templating solution may be all that you need if none of the other libraries that provide templating such as lodash, underscore or handlebars is present.

Template Target (same as above)
Template Source
<!-- template -->
<script id="tmpl-artist" type="text/tmpl">
    <li id="artist_0"></li>
</script>
JavaScript
//jQuery
$(function() {
    var tmplSource = $('#tmpl-artist').html(),
        artistTmplItem;

    $.getJSON('//jimfrenette.com/api/chinook/artists').done(function(data) {
        if (data) {

            for(var i = 0, len = data.length; i < len; i++) {

                artistTmpl = $(tmplSource);

                artistTmplItem = artistTmpl.attr('id','artist_'+data[i].ArtistId);

                artistTmplItem.text(data[i].Name);

                $('ul.artist-list').append(artistTmplItem);

            }
        }
    });
});

Just JavaScript

A JavaScript only solution that does not use jQuery or any other libraries.

Target element (same as Template Target above)
<ul class="artist-list"></ul>
JavaScript
var getJSON = function(url) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.responseType = 'json';
        xhr.onload = function() {
            var status = xhr.status;
            if (status == 200) {
                resolve(xhr.response);
            } else {
                reject(status);
            }
        };
        xhr.send();
    });
};

getJSON('//jimfrenette.com/api/chinook/artists').then(function(data) {
    if (data) {
        // getElementsByClassName returns an array,
        // use the index [0] to get the first element match
        var artistList = document.getElementsByClassName('artist-list')[0],
            li = null,
            da = null;

        for(var i = 0, len = data.length; i < len; i++) {

            li = document.createElement('li');
            da = document.createAttribute('data-artist-id');
            da.value = data[i].ArtistId;
            li.setAttributeNode(da);
            li.appendChild(document.createTextNode(data[i].Name));
            artistList.appendChild(li);
        }
    }
});
Source Code

Benchmarks

Others …

  • doT.js
  • Embedded JavaScript (EJS)
  • jQote2
  • JsRender & JsViews
    JSRender and JsViews together provide the next-generation implementation of both JQuery Templates, and JQuery Data Link - and supersede those libraries.
  • Kite
  • mustache.js
    mustache.js is a JavaScript implementation of the mustache Logic-less templates.
  • NANO
  • Tempo
  • Underscore.js
    A Lo-Dash predecessor, this JavaScript library provides a whole mess of useful functional programming helpers without extending any built-in objects.

Resources

comments powered by Disqus