Javascript Templating

I’ve been using a lot of ajax for a recent application and wanted a really lightweight way to do templating for the responses. Long story short, here is the function that extends the String prototype.

String.prototype.templatize = function (o) {
        return this.replace(
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;


var template = ' \
    <div class="template-test"> \
       <h2>{title}</h2> \
       <p>{content}</p> \

    title: 'This is the title',
    content: 'Hello there, this is a very nice way of making string templates'

Leave a Reply