element creation with templates [ 881 views ]
Goal: to create a quick template based element creation method
Everyday task to manage item templates. We have a container <div id="cont"></div>
and the template of the items.
var tmp = '<div id="%id%" value="%value%">%obj%</div>', itms = [{id: 1, value: 'val1', obj: 'first'},{id: 2, value: 'val2', obj: 'second'}]; console.log(tmp.template(itms)); or $('#cont').html(tmp.template(itms));
the result will be:
<div id="1" value="val1">first</div><div id="2" value="val2">second</div>
to achieve this we have to extend the String object with a template function:
TypeExtend(String, 'template', function(data) { if(data instanceof Array){ var ret = ''; for(i in data){ ret += this.template(data[i]); } return ret; } else{ return this.replace(/%(\w*)%/g, function(m, key) { return data.hasOwnProperty(key) ? data[key] : ""; }); } });
the TypeExtend function itself is here: jump