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.

<code>
String.prototype.templatize = function (o) {
        return this.replace(
            /\{([^{}]*)\}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
</code>

Example:

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

template.templatize({
    title: 'This is the title',
    content: 'Hello there, this is a very nice way of making string templates'
});
</code>

Leave a Reply