Skip to content

Instantly share code, notes, and snippets.

@DragorWW
Last active August 29, 2015 14:02
Show Gist options
  • Save DragorWW/22330a0c755836c7756a to your computer and use it in GitHub Desktop.
Save DragorWW/22330a0c755836c7756a to your computer and use it in GitHub Desktop.
Template.JS - template engine
/**
* 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)
@DragorWW
Copy link
Author

<script type="text/template" id="tpl-templateName">
    <div>
        asd <br>
        {asd} <br>
        {asd|123} <br>
        {asd|} <br>
        {} <br>
        {asd1}
    </div>
</script>

<script>
$(function(){
    asd = new Template('templateName').set('asd','val').get();
asd = new Template('templateName').set('asd','val').getHtml();
})
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment