Working with JavaScript templates using jQuery

I picked up this nifty way of templating HTML code for JavaScript while working at Monkey Quest and haven’t looked back. The idea here is to separate your design from your code. This is particularly useful when you are adding content to your site after the initial rendering. Data can be fed in from a number of sources and added to a page using a template.

Creating an example the old fashion way using concatenation:

//Variables
var title = "Hello World";
var excerpt = "This is the world's shortest lorem ipsum. Jk.";

// Template
var template = "<div style='article'>";
template += "<h1>" + title + "</h1>";
template += "<div style='excerpt'>" + excerpt + "</div>";
template += "</div>";

// Append to "foo" element
document.getElementById("foo").appendChild( template );

While this may work, it’s a nightmare to update your markup as it changes because it’s mixed in with your code and will eventually give you gray hairs.

Consider this piece of markup on your page for your template:

<script type="text/xhtml" id="tmpl-foo">
<div style="article">
	<h1 />
	<div class="exerpt" />
</div>
</script>

That’s very easy to read right? The trick is setting the script type to a value your browser doesn’t know how to render. Try to give it a meaningful mime type but anything that your browser doesn’t know how to render will work.

Now your JavaScript (sprinkled with a little jQuery) could look like this:

// Variables
var title = "Hello World";
var excerpt = "This is the world's shortest lorem ipsum. Jk.";
var template = $( $("tmpl-foo") );

// Set variables in template
template.find("h1").html( title );
template.find("div.excerpt").html( excerpt );

// Append to "foo" element
$("#foo").append( template );

Conclusion

Some people also like to load templates externally by putting the code in a HTML file on the server and using jQuery’s $.get method to pull it in as needed. There are also plugins for jQuery that simply do string replacements in your template string.

Apr 1, 2014 Programming