Last active
December 29, 2016 15:44
-
-
Save tincho/b91f7de0d195af9c581eeda9a5ffaf65 to your computer and use it in GitHub Desktop.
Element.fillWith basic "template filling" function
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
/** | |
* 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