Skip to content

Instantly share code, notes, and snippets.

@filimo
Created September 28, 2016 09:07
Show Gist options
  • Save filimo/5a7b57d23171d04735a75e2244f0d033 to your computer and use it in GitHub Desktop.
Save filimo/5a7b57d23171d04735a75e2244f0d033 to your computer and use it in GitHub Desktop.
function Template(input, tag, options) {
var _options = {
onClone: function(row, data) { },
appendElm: function(elm, val) { elm.text(val); },
replace: false
};
var options = $.extend(_options, options);
var clone = tag;
if (!options.replace) {
clone = clone.clone();
clone.removeAttr("id");
}
function template(input, clone, key) {
function drawArray(val, key) {
var prev;
var _clone = clone.prevAll('[tname="' + key + '"]');
if (_clone.size() === 0) { _clone = clone.find('[tname="' + key + '"]'); }
var first = _clone.clone();
if ($(val).size() === 0) {
_clone.hide();
} else {
if(_clone.size() > 0) {
jQuery.each(val, function(index, val) {
new template(val, _clone, key);
options.onClone(_clone, val);
if (prev !== undefined) {
prev.filter(":last").after(_clone);
}
prev = _clone;
_clone = first.clone();
});
}
}
}
function drawObj(val, key) {
jQuery.each(val, function(_key, val) {
if (key !== undefined) { _key = key + "." + _key; }
draw(val, _key);
});
}
function formater(val, format) {
if (format == undefined) {
return val;
} else {
return $.formater.parse(val, format);
}
}
function drawElm(val, key) {
var elm = $(clone[0]);
if (elm.attr("tname") != key) { elm = clone.find('[tname="' + key + '"]'); }
if (elm.size() > 0) {
var v = formater(val, elm.attr("format"));
options.appendElm(elm, v);
}
}
function draw(val, key) {
if (jQuery.isArray(val)) {
drawArray(val, key);
} else if ((val !== null) && (typeof val === "object")) {
drawObj(val, key);
} else {
drawElm(val, key);
}
}
draw(input, key);
}
new template(input, clone, undefined);
clone.show();
return clone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment