Wednesday, June 18, 2014

JS: Minimalist Templator

This is an evolved version of the previous CTemplator classes that you can refer at Templator, Advanced Templator.

Basically in this, the rarely used methods have been chopped-off and the tagging method with '@' has been deprecated because it is limited to only 10 items array. You can say, it's a loop hole earlier due to which if array items exceeds this limit then while replacing the tag initial tags overwrites the exceeded tags. So this new version came into picture; that have only 2 methods where 'fitIn' uses serial-number or index value while the other one 'fixIn' uses key value of the hash-map array.
@file CTemplator.js
@author Abhishek Kumar
window.CTemplator = {
    fitIn: function (template, arglist) {
        var tag, output = template;
        for (var i = 0, len = arglist.length; i < len; i++) {
            tag = new RegExp("\\[" + i + "\\]", 'g')
            output = output.replace(tag, arglist[i]);
        return output;
    fixIn: function (template, hashtable) {
        var tag, output = template;
        for (var key in hashtable) {
            tag = new RegExp("\\[" + key + "\\]", 'g')
            output = output.replace(tag, hashtable[key]);
        return output;
// Usage
CTemplator.fixIn('<a href="#[Link]" title="[Content]">[Content]</a>', {
    Link: 'test1.html',
    Content: 'Test1'
CTemplator.fitIn('<a href="#[0]" title="[1]">[1]</a>', ['test1.html', 'Test1']);

No comments:

Post a Comment