jQuery Templates Plugin
Documentation
Current Release
templates-1.1.1.zip Download
Overview
The jQuery templates plugin enables you to use jQuery and HTML as a template engine. Why would you want to use JavaScript as a template engine you might ask? One of the primary reasons is to perform easy token replacements inside the DOM when you receive data back from an AJAX call. Typically (especially when using frameworks like jQuery) you won’t want to put your html inside a JS file, but rather use the code to manipulate the html already inside the DOM. The jQuery templates function allows you to apply template token replacements to any section of markup in the DOM, and even clone templates when you have an array of new values.
The basic format of the plugin is as follows:
$( selector ).render( values, options );
selector:
The jQuery selector that targets a template in the html document
values:
A {key:value} set of tokens and replacements,
or an array of {key:value} replacements to be rendered onto
multiple templates
options:
{
clone:
(true|false) Set to true if you want to clone the template,
rather than simply replacing values. Defaults to false.
preserve_template:
By default the template is overwritten with new values,
which means it cannot be used again.
Set preserve_template:true if you want to keep the
un-rendered template in the DOM. Typically you will
want to set your template to display:none so you
can't see the un-rendered tokens.
Defaults to false.
beforeUpdate: Callback to do an action before the template is
updated with values.
function( new_node ) {}
afterUpdate: Callback to do an action after the template is updated
and rendered in the document.
function( new_node ) {}
}
Example 1: A Simple Replacement
Tokens are defined in the html using the curly braces as follows:
<div id="hello_world" >
It is said, every great programmer begins with:
{token1}, <span>{token2}</span>
</div>
A simple example finds the DOM node with div id=”hello_world” replaces the all tokens inside:
$(document).ready( function()
{
$('#hello_world').render( {
'token0': 'hello_world',
'token1': 'hello',
'token2': 'world'
});
});
Example 2: Lots of Templates
Now, lets consider some different html where we want to do replacements on several templates:
<div class="mytemplate" >Some people say {token0}, {token1}</div>
<div class="mytemplate" >Other people say {token0}, {token1}</div>
The code example below renders several elements on the page with the same set of values. So all elements in the document with class=”mytemplate” have token0 and token1 set to hello and world.
$(document).ready( function()
{
$('.mytemplate').render( {
'token0': 'hello',
'token1': 'world',
});
});
The above code renders:
Some people say hello, world Other people say hello, world
Example 3: Lots of Templates, Different Values
A more sophisticated example renders several elements on the page with different values – just pass an array! Each separate element of the array applies a different set of values to each match of the selector. So elements in the document with class=”myclass” have token0/token1 set to hello/world for the first match, and foo/bar for the second match.
$(document).ready( function()
{
$('.mytemplate').render(
[
{ 'token0': 'hello', 'token1': 'world'},
{ 'token0': 'foo', 'token1': 'bar'}
]);
});
The above code renders:
Some people say hello, world Other people say foo, bar
Example 3.5: Nested Data Structures
Now, what happens if you have a nested data structure like an array of arrays of arrays? Pretty simple, the jQuery Templates plugin gives you access to all your data using {key1.key2.key3} style tokens.
<div id="lotr" >
<ul>
<li>{halflings.0.name} has {halflings.0.armor} armor</li>
<li>{halflings.1.name} has {halflings.1.armor} armor</li>
</ul>
</div>
Notice that numeric array items can be accessed using the halflings.0 or halflings.1. The code to render the above template is shown below:
$(document).ready( function ()
{
$('#lotr').render( {
'halflings' : [
{'name': 'frodo', 'armor':'mithril'},
{'name': 'sam', 'armor': 'cloth' }
]
});
});
Example 4: Selector Replacements
The jQuery Templates Plugin supports the concept of sub-templates. You can use a jquery selector as a string key in your replacements array and all matching elements inside your template will be treated as a sub-template. Consider the html below:
<div id="mytemplate" >
Dogs say <span>...{dog_sound}</span>, <strong>...{dog_sound}</strong>
<p>But pigs say {pig_sound}!!!</p>
But you should see these tokens: {dog_sound}, {pig_sound} because they don't match the selector.
</div>
In the above example we need to target tokens in some contexts, but not in others. To do this, we can use jQuery selectors to target only the elements where we want the token replacements applied. Each match becomes a sub-template of the parent template. See the code below…
$(document).ready( function ()
{
$('#mytemplate').render( {
'$("span, strong, p")': { dog_sound: 'woof', pig_sound: 'oink' }
});
Dogs say …woof, …woof
But pigs say oink!!!
But you should see these tokens: {dog_sound}, {pig_sound} because they don’t match the selector.
Example 5: Clones!
Now, if templates weren’t fun already, here is an example that will surely excite! jQuery templates allow you to optionally clone and replace elements in a single call. Consider a list element template that you want to replicate an array of values into:
<ul>
<li id="clone_me" class="template {rendered_class}" >The clone is: {your_value}</li>
</ul>
The code below will clone the element with id=clone_me and create a set of new elements with the rendered values directly beneath the template. Notice the second argument to render accepts an options argument with clone set to ‘true’ in this example: $(selector).render(values,{clone:true});
Also take note that when you clone a set of values, you must pass a numeric array. Each entry of the array will create a clone with a different set of values. In this example, the template itself will be removed from the page, however, if you want to keep it around to clone more later, add the “preserve_template:true” option: $(selector).render(values,{clone:true, preserve_template: true});
$(document).ready( function ()
{
$('#clone_me').render(
[
{
'rendered_class': 'rendered',
'your_value' : 'clone1'
},
{
'rendered_class': 'rendered',
'your_value' : 'clone2'
}
], {clone:true} );
The rendered values look like this:
The clone is: clone1 The clone is: clone2
Example 6: Clones – With Sub-Templates!
Now, this one should boggle the mind with sheer posibilities! Here is an example that allows you to optionally clone and replace elements in a sub-template. Sub-templates can be cloned by using a jquery-style selector, but instead of $(”selector”), we use @(”selector). The @ means “clone” in the jQuery template plugin.
<div id="lotr" >
{who_says}'s Famous Quotes:
<ul>
<li class="halfling_tmpl">{name} has {armor} armor</li>
</ul>
</div>
The code below will clone the li.halfling template inside the parent template, designated by ‘@(”li.halfling_tmpl”)’. The values of each element of the array get applied to each new clone created from the sub-template!
$(document).ready( function ()
{
$('#lotr').render( {
'who_says': 'Aragorn',
'@("li.halfling_tmpl")' : [
{'name': 'frodo', 'armor': 'mithril'},
{'name': 'sam', 'armor': 'cloth' },
{'name': 'pippin', 'armor': 'accidental' }
]
}, {clone: true} );
});
The rendered values look like this:
Aragorn's Famous Quotes:
* frodo has mithril armor
* sam has cloth armor
* pippin has accidental armor