R
B
code

Robert Tamayo's Code Blog

Simple Javascript Template

Javascript templating frameworks separate code from html. They also keep things clean. Let's say you have two variables, className and content, and need to use them to create a message somewhere on your page in an async callback function.

var className = 'message'; 
var content = 'Message from the asynchronous universe.';

Without templates, you might be tempted to concatenate strings. Even with one line, this can get hard to follow.

var div = '<div class="' + className + '"><div class="inner">' + content + '</div></div>';

Worse, if you have to something else to the div later, then the whole thing gets even more cluttered. It gets really tricky to keep track of nested divs.

The traditional way to create DOM elements with javascript would be this technique:

var innerDiv = document.createElement('div');
innerDiv.classList.add('inner');
innerDiv.innerHtml = content;
var outerDiv = document.createElement('div');
outerDiv.classList.add(className);
outerDiv.appendChild(innerDiv);

However, you can quickly wind up with more and more lines of code as you add nested elements, making keeping track of the order of appending child elements an unintended focus.

A javascript template looks like this:

<div class="{{className}}">
    <div class="inner">
        {{content}}
    </div>
</div>

What you do is feed the template into a function, pass in data, and let the template engine change it into what you want. There are a bunch of template engines out there, including moustache.js and handlebars.js. You can do javascript templating without having to learn either of those, however. Just create your own template rendering engine.

var Template = (function() {
    var _regex = /{{[\w\s:\|]+}}/g;
    
    return {
        render: function(html, data){
            var name;
            var matches = html.match(_regex);

            for (var i = 0; i < matches.length; i++) {
                name = matches[i].replace("{{", "").replace("}}", "");
                if (data[name]) {
                    html = html.replace(matches[i], data[name]);
                } else {
                    html = html.replace(matches[i], "");
                }
            }
            return html;
        }
    }
}());

Elsewhere, place your html template on the page like this:

<script type="text/template" id="message-template">
    <div class="{{className}}">
        <div class="inner">
            {{content}}
        </div>
    </div>
</script>

Then run the data through the template function:

var templateHtml = document.getElementById('message-template').innerHtml;
var templateData = {
    className: "message", 
    content:  "Message from the asynchronous universe."
};
var renderedHtml = Template.render(templateHtml, templateData);


Comments:
Leave a Comment
Submit