jQTemplate is a jQuery plugin that provides a clean and powerful way to dynamically build DOM elements from JavaScript. It eliminates the often messy element generation in JavaScript and allows the developer to define HTML templates in a nice readable fashion.
You might be asking “why yet another jQuery templating engine?”. I needed an engine with the following qualities:
I felt that nothing out there filled my requirements. The google-jstemplate engine did provide most of the features I was looking for but I really was looking for something that had jQuery integration. This library is very much inspired by google-jstemplate.
Lets take a simple example: generate a bullet list from elements in an array.
$().ready(function() {
$("#template > ul").jqtemplate({
list: ["So", "Freakin", "AWESOME!"]
});
});
<div id="template" style="display: none">
<ul>
<li jqloop="{object: 'val', array: $this.list}"
jqtext="$this.val" />
</ul>
</div>
And a more advanced example: generate a bullet list from the array, bind some events, and set an attribute.
$().ready(function() {
$("#template > ul").jqtemplate({
rand: function() {
return 8 + (Math.random() * 20);
},
onHover: function() {
$(this).css("background-color", "cyan");
},
onLeave: function() {
$(this).css("background-color", "white");
},
list: ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
});
});
<div id="template" style="display: none">
<ul>
<li jqloop="{object: 'item', array: $this.list}"
jqbind="[{event: 'mouseenter', fn: $this.onHover},
{event: 'mouseleave', fn: $this.onLeave}]"
jqattr="{style: 'font-size: ' + $this.rand() }"
jqtext="$this.item" />
</ul>
</div>
A template is comprised of regular HTML (usually hidden) with special attributes that are evaluated to produce some dynamic content in the DOM.
The attributes are evaluated as JavaScript. An object model is used to provide the context of the attribute evaluation and exposed as an object named ‘$this’.
jQuery.jqtemplate(model, options)
The latest version (0.4) is available here.
You can browse the source in the git repository.
Licensed under the GPL.