Last active
August 29, 2015 14:02
-
-
Save DragorWW/22330a0c755836c7756a to your computer and use it in GitHub Desktop.
Template.JS - template engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Template.JS v 0.1 | |
* @author Andreev Sergey | |
* @corp USERSTORY | |
*/ | |
(function($) { | |
/** | |
* Template engine class | |
* @param {string} tpl template name | |
* @param {array} o @optional options array | |
*/ | |
Template = (function(){ | |
function Template(tpl, o) { | |
var | |
html, | |
options, | |
prefix; | |
tpl = (typeof tpl === "undefined")? false : tpl; | |
o = (typeof o === "undefined")? false : o; | |
//init | |
options = { | |
selector: o? o.selector : '#', | |
prefix: o? o.prefix : 'tpl-', | |
letterLeft: o? o.letterLeft : '{', | |
letterRight: o? o.letterLeft : '}', | |
isDefaultParams: o? o.isDefaultParams : true, | |
isRemoveEmptyParams: o? o.isRemoveEmptyParams: true | |
}; | |
tplElm = options.selector + options.prefix + tpl; | |
// private functions | |
var setHtml = function() { | |
html = $(tplElm).clone().html(); | |
} | |
var setParam = function(param, value) { | |
if (param && value) { | |
var find = options.letterLeft + param + '\\|?.*' + options.letterRight; | |
html = html.replace(new RegExp(find, 'g'), value); | |
} | |
}; | |
var setDefaultParams = function() { | |
var find = options.letterLeft + '..*\\|(.*)' + options.letterRight; | |
html = html.replace(new RegExp(find, 'g'), '$1'); | |
} | |
var removeEmptyParams = function() { | |
var find = options.letterLeft + '..*\\|?.*' + options.letterRight; | |
html = html.replace(new RegExp(find, 'g'), ''); | |
} | |
tpl && setHtml(); | |
options.isDefaultParams && setDefaultParams(); | |
options.isRemoveEmptyParams && removeEmptyParams(); | |
this.setTpl = function(id) { | |
setHtml(); | |
return this; | |
} | |
/** | |
* Set HTML string template | |
* @param {string} tpl | |
*/ | |
this.setHtml = function(tpl) { | |
html = tpl; | |
return this; | |
} | |
/** | |
* Set param or params | |
* @param {string|array} param1 | |
* @param {string} param2 @optional | |
*/ | |
this.set = function(param1,param2) { | |
if (typeof param1 === 'object') { | |
$.each(param1, function(key, value) { | |
setParam(key, value); | |
}); | |
} else { | |
setParam(param1,param2); | |
} | |
return this; | |
} | |
this.get = function() { | |
return $(this.getHtml()); | |
} | |
this.getHtml = function() { | |
return html; | |
} | |
} | |
return Template; | |
})(); | |
})(jQuery) |
Author
DragorWW
commented
Jun 10, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment