Here is the advanced version of template manipulating class CTemplator in javascript. The basic version can replace just one key-tag in the provided template per item in hastable. While this advanced class having the method
CTemplator.fitIn4()
can update any occurrence of the key-tags in the provided template and replaces them with the related item in the hashtable. That means, say a template have multiple tag of name then all of them will get replaced by single item in the hashtable.
/*
@file CTemplator.js
@author Abhishek Kumar
@email akbittu@gmail.com
*/
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;
},
fitIn3: function (template, hashtable) {
var key, tag, output = template;
for (key in hashtable) {
output = output.replace(key, hashtable[key]);
}
return output;
},
fitIn4: function (template, hashtable) {
var key, tag, output = template;
for (key in hashtable) {
tag = "\\[" + key + "\\]";
tagx = new RegExp(tag, 'g')
output = output.replace(tagx, hashtable[key]);
}
return output;
}
};
/*
// Usage
CTemplator.fitIn1('<a href="#[Link]" title="[Title]">[Content]</a>', {
Link: 'test1.html',
Title: 'Test1',
Content: 'Test1'
});
CTemplator.fitIn4('<a href="#[Link]" title="[Content]">[Content]</a>', {
Link: 'test1.html',
Content: 'Test1'
});
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']);
CTemplator.fitIn3('<a href="#Link" title="Title">Content</a>', {
Link: 'test1.html',
Title: 'Test1',
Content: 'Test1'
});
*/
Comments
Post a Comment