Skip to content

Instantly share code, notes, and snippets.

@rmurphey
Created February 27, 2011 22:02
Show Gist options
  • Select an option

  • Save rmurphey/846590 to your computer and use it in GitHub Desktop.

Select an option

Save rmurphey/846590 to your computer and use it in GitHub Desktop.
jQuery templating mini-demo
$(function() {
var people = [
{ first : 'Paul', last : 'Irish', img : 'paul.png' },
{ first : 'Rebecca', last : 'Murphey', img : 'rebecca.png' },
{ first : 'Alex', last : 'Sexton', img : 'alex.png' },
{ first : 'Adam', last : 'Sontag', img : 'adam.png' }
],
myList = $('#myList');
var html = $.map(people, function(person) {
return '<li>' +
'<img src="img/' + person.img + '" alt="' +
person.first + ' ' + person.last + '" /> ' +
person.first + ' ' + person.last +
'</li>';
}).join('');
myList.html(html);
/* */
/* *
// ohai templates
var myTemplate = '<li>' +
'<img src="img/${img}" alt="${first} ${last}" /> ' +
'${first} ${last} ' +
'</li>';
$.each(people, function(i, person) {
$.tmpl(myTemplate, person).appendTo(myList);
});
/* */
/* *
// auto-iteration ftw
var myTemplate = '<li>' +
'<img src="img/${img}" alt="${first} ${last}" /> ' +
'${first} ${last} ' +
'</li>';
$.tmpl(myTemplate, people).appendTo(myList);
/* */
/* *
// get our template from a script tag in the page,
// save it somewhere we can use it later, and
// "compile" it while we're at it so it will run
// faster? no way!
$('#personTemplate').template('saveForLater');
$.tmpl('saveForLater', people).appendTo(myList);
/* */
});
@mathiasbynens

Copy link
Copy Markdown

FTR, the documentation for jQuery Templates can be found here: http://api.jquery.com/category/plugins/templates/
The source code is on GitHub, too: https://github.com/jquery/jquery-tmpl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment