While working on a project I found myself generating quite a lot of HTML with jQuery so I made myself a really simple template system.
I was surprised of how dead simple it was, thanks to my string formatting library:
$.tpl = function() {
var out = '';
if (!arguments[1]) {
out = this[arguments[0]];
}
else if ($.isArray(arguments[1])) {
out = this[arguments[0]] = arguments[1].join('');
}
else if (typeof(arguments[1]) == 'object') {
out = $.format(this[arguments[0]], arguments[1]);
}
return $(out);
};
It doesn't get much simpler than this.. Using it is quite straight forward too:
Creating the template
$.tpl('tweet', [
'<div id="tweet-{id:s}" class="tweet">',
'<div class="tweet-body"><b>@{from:s}</b>: {body:s}',
'(<a href="{href:s}" class="tweet-date">',
'<abbr title="{timestamp:s}">{timesince:s}</abbr>',
'</a>)',
'</div>',
'</div>'
]);
Rendering
$.getJSON('/tweets/username/', function(resp, s){
$.each(resp.tweets, function(idx, tweet) {
$.tpl('tweet', {
id: tweet.id,
body: tweet.body,
from: tweet.screen_name,
timestamp: tweet.pub_time,
timesince: $.timeago(tweet.pub_time)
}).appendTo('#tweet-list');
});
});
I've added it to my jquery.utils library. I know what you're thinking and no I won't implement template inheritance, maybe inclusions but don't hold your breath for it.
I <3 jQuery.
I've checked all over the project pages and wiki for the template system. Is it in jquery.utils.js, but just not documented anywhere?
@Justin
I've just added the documentation to the jquery.strings.js wiki page:
http://code.google.com/p/jquery-utils/wiki/StringFormat?ts=1228769920
Although, there isn't much more to document for now..
Also see Douglas Crockford's String.supplant()
Very nice addition to Javascript.
david