There are a few templating libraries available which you could use to create templates for your apps. While its easy enough to learn how to use them you could also just as easily create your own external template files for your jQuery-based projects using the jQuery skills you already have. Discussed here is a simple way of including HTML templates into your jQuery work.

Introduction

Templates provide a way of separating layout from code. As such, they have various methods of indicating where data is to be inserted into the template. In our case we’ll use class and ID selectors in the HTML itself and thus be able to use jQuery’s existing methods to manipulate the template.

The data to be inserted into our templates can take the form of strings, numbers, objects or some sort of array. Arrays mean that you likely have a repeating region. The available templating libraries (Underscore, Handlebars, etc) or frameworks that have built-in templating (Sencha Touch, Angular, etc) provide methods that abstract the process of looping through arrays to display lists or tables. These libraries and frameworks also provide helper functions for things such as string formatting and conditional logic to add intelligence to the template.

While built-in helper methods are a handy feature this article will assume that you’ll build your own by leveraging jQuery’s features. For our purposes I’ll assume that you only need the most basic type of template and that will be one that has identified in some way what portions of the template itself will be used/substituted or otherwise populated with your desired data.

Setup a Template

Our template will be an HTML file – a properly formed file complete with all of the required HTML elements, ie., html, head, title & body tags. Basically, you will layout your page so that it represents one specific type of view within your application. Save your templates in a folder called “templates” in some logical area of your app/site.

While you are laying out your page you are naturally creating CSS class and ID selectors for you page elements. While you are doing this you are also likely using greeked-in text or “for-position-only” images so that you can realize your layout. Also, you should build the template with an eye towards the areas that need to be populated with text, images or whatever the case might be. With this last point in mind you should pay attention to the class/ID selectors that you give to your DOM elements as that will be what we use to manipulate the template.

Since we mentioned CSS, your style sheet should be an external style sheet that your app/site loads up. This way when the template is used all of the necessary styling will already be present. If you are the sort that doesn’t want stylesheets loaded that aren’t yet needed then figure out a way to inject them into your page – we are using jQuery so this should be an easy task – understand that today’s discussion is only about templates not dependency management 🙂 (though honestly, the link to the external CSS could be added to the template HTML, then you create a query selector to grab it when the template is loaded and then….. but I digress…)

Sample Template

Here’s a sample template from a project that I recently worked on.



    

    

Pretty basic. Note that the actual template is the one with the #interactive ID. The rest of the page is just filler for the layout guys on my team.

Within the #interactive DIV I used ID selectors for the elements that would need to be populated with text. Also, while I didn’t keep any dummy text in the template you could easily insert greek text so that you can see what the layout looks like without having to first run it through your app. That’s the nice part about using this kind of templating workflow, that your teammates can focus on layout while you focus on developing the application without worrying about stepping on each other’s work.

Worth noting here is that like in any project you have a header and a footer. The same with this template. Recall that we mentioned that it was nice to be able to look at a template outside of your application to see it in its entirety without impacting development. That would assume that the header and footer be present even though it isn’t needed. You could of course elect not to include these two page features for many reasons, not the least of which would be to make a smaller template file that loads that much faster. This example for better or worse includes the header (denoted by the topBlueBar and logo ID’s) and the footer (denoted by the controlsWrapper).

It is of course true that you can add some automation via Gulp or similar to strip the header and footer from the templates in order to give the layout guys the benefit of viewing their work in-context and the more picky developers the desire to strip out what would be considered wasteful…. however you want to deal with it, its entirely up to you. Again, both header and footer are presented here and will be dealt with in the next section.

Before we proceed look at that wrapping div element on line 5 – this is **necessary** as without it the template will not work in the way that we might expect. We’ll explain why in the next section.

Load the Template

This is the most difficult part (not that its at all difficult) – loading a template. You simply need to make an AJAX call to load up the file. Here’s an example:

var _templates = {}; // save your templates so that you can re-use them
$.get('templates/content_tpl.html', function(template){
    // in this example, we're calling the template "sample_template" and assigning the template as a DOM object as its value
    _templates.sample_template = $('
').append($($.parseHTML(template)).find('#interactive').html()); });

Hopefully the above is clear but lets quickly break things down.

First, $.get() loads data from the server using a GET request. We are passing the local path to the desired template HTML file.

Next, the file that is returned to us is text which isn’t as useful to us as it could be so we convert it into an array of DOM nodes. This is crucial so that we can use jQuery’s DOM-manipulation methods on the template instead of having to resort to string or regular expression methods.

Now that the page has been converted to jQuery DOM nodes we look for the template area itself which is denoted by the DIV with the #interactive ID.

Finally we assign the resulting DOM nodes to a property of the _templates element so that we can use it in the future.

Interestingly we now can get back to that wrapping DIV mentioned in the previous “Sample Template” section. Without it in place our #interactive query selector won’t work because what will happen is that jQuery will search the first DIV in the page, which of course doesn’t contain the div#interactive element. By wrapping everything in a DIV jQuery is then able to traverse all the nodes and find the desired element.

In case you didn’t realize what just happened – we extracted only the template HTML from the template. Everything else is being discarded. So the header and footer HTML that was part of the template HTML file itself is not what we will be working with moving forward.

Using the Template

Recall that we converted the string result of the AJAX get to DOM nodes, that we pulled out only the nodes that we needed, and that we saved the result to _templates.sample_template.

Using the template is simple: do what you always do in a page where you want to change the values or inner html of page elements:

// get a deep copy of the template
var tpl =  JSON.parse(JSON.stringify(_templates.sample_template));

// populate the template
tpl.find('#title').html('This is my first template');
tpl.find('#subTitle').html('This is a subtitle');

// now insert the template html into your app
// where our app already has a #templateArea DIV within it so
// this is a simple insert 
$('#templateArea').html(tpl.html());

Notice that we can easily manipulate our template using the usual jQuery DOM manipulation methods. Also, it would be a simple matter to pull out a chunk of DOM nodes to iterate through a list and then reinsert them back into the tpl.

From here you can start to flesh out your home-grown templating system. Adding methods for formatting dates, dollar amounts, or handling repeating areas like lists or tabular data.