Using JQuery Templates

Recently I was working on a project that required the user to add a date range then add the times for each day within that range. After looking into doing this the old fashioned, embed it in the javascript, way I decided to look at using jQuery templates where the content is defined in a templating language then loaded at run time and the data is injected into the template.

A case study
The project I was using this technology with required that the user select a start and end date then the interface would respond and create time picker fields for each day selected. The advantage of using the templates in this instance was that if anything needed to be changed in the template it would be far easier than if the html elements had been declared and added in jQuery.

A jQuery snippet adding dynamic html

var html ='
<div data-id="' +  obj.id + '">' +
'<img src="' + src + '" alt="" />' +
'<input class="linkto" type="text" value="' + obj.url + '" placeholder="Linked url" />' +
'<input class="remove-button button-primary" type="button" value="Remove Icon" data-id="' + obj.imageid +'" />' +
' <input class="moveup-button button-secondary" type="button" value="Move Up" />' +
'<input class="movedown-button button-secondary" type="button" value="Move Down" />' +
'</div>
';

A jQuery template:

<script id="dateTemplate" type="x-jquery-tmpl">
<div data-id="${id}">
	<img src="${src}" />
    <input type="text" class="linkto" placeholder="Linked url" value="${url}"/>
    <input type="button" class="remove-button button-primary" data-id="${imageid}" value="Remove Icon" />
    <input type="button" class="moveup-button button-secondary" value="Move Up">
    <input type="button" class="movedown-button button-secondary" value="Move Down">
</div>
</script>

The advantage here is that we can change this easily and we don’t have any nasty apostrophes all over the place. To get started with this technology head over to https://github.com/BorisMoore/jquery-tmpl and include a copy of the js in your project. After creating a template we can load it like so:

$.get('js/create/step_two/_date.tmpl.htm', function(templates) {
$('body').append(templates);
});

We then append and render the template using something like the following:

var item = {
day: weekday[dateTime.getDay()],
pId: id,
dId: i,
date : dateTime.getTime()
};
//Add the template
$('#dayTemplate').tmpl(item).appendTo(container);

Importantly jQuery templates have now been superseeded by JsRender: http://www.jsviews.com/#jsrender

To the top
css.php