Tuesday, January 14, 2014

JS: Templator

Here is the template manipulating class in javascript. There are 2 methods present in this class for doing the same thing but in 2 different ways. Based on requirement or comfort-level, the particular method can be chosen.
@file CTemplator.js
@author Abhishek Kumar

// Class
var CTemplator = {
    fitIn1: function (template, hashtable) {
        var key, tag, output = template;
        for (key in hashtable) {
            tag = "[" + key + "]";
            output = output.replace(tag, hashtable[key]);
        return output
    fitIn2: function (template, arglist) {
        var output = template;
        for (var i = 0; i < arglist.length; i++) {
            output = output.replace(new RegExp('@' + i, 'g'), arglist[i]);
        return output;

// Usage
CTemplator.fitIn1('<a href="#[Link]" title="[Title]">[Content]</a>', {
CTemplator.fitIn1('<a href="#[Link]" title="[Content]">[Content]</a>', {

CTemplator.fitIn2('<a href="#@0" title="@1">@1</a>', ['test1.html', 'Test1']);
CTemplator.fitIn2('<a href="#@0" title="@2">@1</a>', ['test1.html', 'Test1', 'Test1']);
There are 4 examples provided above to describe different scenarios:
  • The first example shows that the hash-array-map like object has been used for mapping each keyword present in the template. 
  • The second example shows that there could be multiple occurrence of particular keyword that would get replaced by same value which is mapped in the object.
  • The third example shows that instead of using hash-map, we can also use simple array like list where the keyword is mapped with index of the provided argument array. 
  • The fourth example shows the multiple occurrence of particular keyword and their mapped values in the list.

No comments:

Post a Comment