Simple JavaScript templating with jquery-tmpl

Steve Robinson

5 min read

When writing applications where you fetch data asynchronously from the server and render it to the user using AJAX you would have to deal with building DOM elements that would markup(v) the data. One way to avoid writing ugly looking strings of HTML in your JavaScript is to fetch the markup(n) directly from the server. But that would mean blurring the lines of separation of concerns. It would be nice if you had some kind of template HTML with placeholders for data where you could drop in the data fetched from your server and render it to the user. Well, JavaScript templating engines provide just that!
I said templating engines. Yes there are several engines that would cater to such needs of yours. But in this post we are going to look at a very basic yet powerful but relatively old engine, the JQuery Template or simply JQuery Tmpl. Its pretty easy to use. This post will be a small tutorial to using JavaScript templates for people who haven’t tried templating before. We will go through the basics of JQuery templates and then see an example usage.

Firstly to use JQuery template you need to include the jquery-tmpl javascript file. You can get this at the above mentioned repository. Or go here(https://github.com/BorisMoore/jquery-tmpl/blob/master/jquery.tmpl.min.js) and copy the contents and save it in a file with whatever name you want. Lets use ‘jquery.tmpl.min.js’ (same as in the source).
You also need JQuery. You can get JQuery 1.10 here(http://code.jquery.com/jquery-1.10.2.min.js). Save this also in the similar way.
We’ll start with where we place our templates. The templates can be placed in a script tag blog with the type attribute set as ‘text/x-jquery-tmpl’ like below.
[sourcecode language=”html”]

[/sourcecode]
or they can he held in a variable like this,
[sourcecode language=”javascript”]var template = ‘

Hello!

‘;[/sourcecode]
Alright before starting to learn how to write templates we must know what kind of data can be passed to a template. Well a JavaScript object is passed to the template. A JavaScript object is just a set of key and value pairs. Value can be any data or function. In this case we will use only data. So a sample Object would be,
[sourcecode language=”javascript”]var steve = {‘Name’: ‘Steve Robinson’, ‘Age’:22, ‘Country’:’India};[/sourcecode]
We could also pass an array of such objects to the template and we can iterate through each object of the array. We will see how to do that and how to reference this data inside the template now.
As we said before a template is just HTML code with placeholders for dropping in data. The placeholders are enclosed by the characters ${ }. So if you want to place the value of the key ‘Name’ in a certain position in the template, you would use ${ Name }. For example, let us see a sample template to display the above object.
[sourcecode language=”javascript”]

[/sourcecode]
Now seeing this I think you might have some idea as to how templates work. So now we have a template and also an object to power the template. How do we make the connection? Dont worry. Its pretty simple to apply the data onto the template and generate the HTML.
Then magic function that we use for this is the tmpl() function. The syntax of this is as follows:
[sourcecode language=”javascript”]$.tmpl(template,[data],[options]);[/sourcecode]
This returns the HTML elements that were generated from the template. Okay. The template can be a template string, or a JavaScript variable having the template string or it can be a HTML element that encloses the template.
JQuery tmpl provides some options to alter the way templates are rendered. But that is out of the scope of a beginners introduction. Lookup at the Github page of the project to learn more.
Okay. In our example we have our template enclosed in a tag. So we need to select this element and use it as the template argument. Lets use the ID to select the element and lets call the template function tmpl() like this:
[sourcecode language=”javascript”]$.tmpl( $(‘#person-template’), steve).appendTo(‘targetLocation’);[/sourcecode]
Okay most of this might look straight forward to you except for the last appendTo() call. Alright. I told you that the tmpl() function returns HTML elements right? What do you do with this? You would append it somewhere in your HTML document! That is exactly what we are doing here. Instead of appendTo we can also use prependTo or any JQuery function to help render the returned HTML/DOM elements. The following jsfiddle illustrates this example.
http://jsfiddle.net/steverob/B3d4y/
The above call despite following the syntax to the word looks kind of clumsy. If you feel so, you could also use the following syntax that is more elegant.
[sourcecode language=”javascript”]$(‘#person-template’).tmpl(steve).appendTo(‘targetLocation’);[/sourcecode]
There is one thing that must be noted. When you pass the template to the tmpl() function, the first thing that happens is, the template gets compiled and a compiled template is created and the data is applied to this compiled template only. So every time we call tmpl, the template gets compiled. This is pretty inefficient right? Yes it is. And that’s why we have the template() function that compiles a template and generates a named template. This named template can be used in the tmpl() function and it will not be complied every time. We do this as follows:
[sourcecode language=”javascript”]$.template( “compiledPersonTemplate”, “person-template” );[/sourcecode]
Now all we have to pass to the tmpl() as the first argument is “compiledPersonTemplate”.
So now you know what JQuery Templates are and how you can write them. Now let us see the various statements you can utilize in templates.
The first one I’d like to show is the {{each Collection}} {{/each}} statement. Like I said before, the data can be an array of objects with a key. In that case this each statement will help you to iterate through each of them. For example, if we have the following data:
[sourcecode language=”javascript”]var steve = {‘Name’:’Steve’,’Skills’:[{‘Skill’: ‘Rails’},{‘Skill’: ‘HTML’},{‘Skill’: ‘JQuery’}]};
[/sourcecode]
We can have the following template to render this:
[sourcecode language=”javascript”][/sourcecode]
It must be noted that if the data is just an array of objects, the template will automatically be repeated for every object and HTML elements will be rendered for each object in the array. i.e No need to use {{each}}. Check out the following fiddle.
http://jsfiddle.net/steverob/7XkxJ/1/
The next one is a fairly familiar one. Its {{if}} {{else}} {{/if}} statement. As you might have guessed, it is used to check for a condition and render content based on that.
The next one is {{html}}. Till now we have rendered plain data without any markup in the template at the placeholders ( ${ } ). But what if we would want to render HTML code? In that case we would have to use the {{html xxx}} statement, where xxx maybe a key to the data object or a JavaScript statement that returns HTML. For an illustration checkout the following jsfiddle.
http://jsfiddle.net/steverob/kxX5T/1/

The last one and the most interesting one is the {{tmpl ([data],[options]) template}} tag. This allows you to render a template inside another template! To illustrate this we will use the previous example. We have the following data,
[sourcecode language=”javascript”]var steve = {‘Name’:’Steve’,’Skills’:[{‘Skill’: ‘Rails’},{‘Skill’: ‘HTML’},{‘Skill’: ‘JQuery’}]};
[/sourcecode]
In the previous example we used a single template to render this. In this we will use template composition (nesting of templates) using the {{tmpl}} tag.
[sourcecode language=”javascript”]
[/sourcecode]
As we can see the ‘#skills-template’ is being called from the original template to and the Skills collection is passed as the data. This can be better understood using the following jsfiddle.
http://jsfiddle.net/steverob/EvdZ3/1/
Yep. This is what JQuery templates are all about. Atleast mostly. You can check its GitHub page (see link I gave earlier) to learn the things I’ve missed out. As I said before this is a very simple templating engine. There are more sophisticated and advanced ones like Handlebars, Moustache etc. Check them out too. Hope you enjoyed this.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *