Javascript Template Management

To the time strapped application developer, templating systems are a godsend. By moving content creation away from jQuery, templates can greatly reduce overall development time while enhancing the maintainability of javascript-based applications.

The trouble is that templates—being neither a part of the HTML spec nor valid Javascript in their own right—don’t really have a natural place in either world. Many asset-management libraries include support for ‘scriptifying’ templates during deployment, but during development it makes fine sense to keep everything out in the open. But how to manage them from there?

The syntax may vary, but I generally develop templates following Underscore’s ERB-style:

<!--
 -  Template for a basic article
 -->
<script type="text/template" class="template" id="Article">
<article>
    <h1><%= title %></h1>
<% if(content) { %>
    <p><%= content %></p>
<% } else { %>
    <p>This article hasn’t been written, yet!</p>
<% } %>
</article>
</script>

Now, I have no problem storing one or two templates inline. On bigger projects with larger teams, though, it makes good sense to keep assets separated as much as possible. I’ve recently settled into a pattern that keeps all templates stored in a single library file that can be dynamically loaded at runtime.

<!-- js/templates.html -->
<div>
    <script type="text/template" class="template" id="Article">
        <!-- ... -->
    </script>
</div>

When the application loads, each template is exposed to my application by it’s id attribute:

// define a namespace
var app = {
    template: null
};

$(document).ready(function(){

    // load template library
    $.get('js/templates.html',function(result){
        $('script.template', $(result)).each(function(){
            app.template[this.id] = _.template( $(this).html() );
        });
    });
}

I’m using Underscore’s template function, but templates can be parsed using just about anything. Once loaded, however, templates can now be used to create DOM-ready content throughout the application:

var article = {
    title: 'hello, world!',
    content: 'this is a new article'
};

$(document).append( app.template.Article( article ) );

Events still need to be handled with jQuery, of course, but adopting this pattern helps keep javascript out of the business of presenting content.

Let’s keep in touch

Get noise-free updates on software, product, and process.

Hey, I'm RJ: digital entomologist and intermittent micropoet, writing from the beautiful Rose City.