Skip to content

Instantly share code, notes, and snippets.

@tincho
Last active December 29, 2016 15:44
Show Gist options
  • Save tincho/b91f7de0d195af9c581eeda9a5ffaf65 to your computer and use it in GitHub Desktop.
Save tincho/b91f7de0d195af9c581eeda9a5ffaf65 to your computer and use it in GitHub Desktop.
Element.fillWith basic "template filling" function
/**
* replaces variables in element innerHTML, e.g.
* DOM: <span id="fillMe">hey {{#}}, whats up {{#}}</span>
* Code: document.querySelector('#fillMe').fillWith('bro')
* Output: hey bro, whats up bro
*
* DOM: <span id="fillMe">the {{animal}} is sitting at the {{forniture}}</span>
* Code: document.querySelector('#fillMe').fillWith({'animal': 'cat', 'forniture': 'table'});
* Output: the cat is sitting at the table
*/
Element.prototype.fillWith = function(data) {
var content = this.innerHTML;
if (typeof data !== 'object') {
data = {'#': data};
}
Object.keys(data).forEach(function(k) {
var exp = new RegExp('\{\{' + k + '\}\}', 'g');
content = content.replace(exp, data[k]);
});
this.innerHTML = content;
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment