Last active
August 29, 2015 14:04
-
-
Save Fardinak/5d9aaa853145a4a23eb5 to your computer and use it in GitHub Desktop.
A simple JavaScript Template Engine
This file contains hidden or 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
/* | |
* A simple JavaScript Template Engine | |
* | |
* By default replaces every {{ foo.bar }} with the | |
* the respective value from provided data object. | |
*/ | |
/* | |
* Return the value addressed in args from obj | |
* | |
* @param key/value pair object to read from | |
* @param array the namespace array | |
* | |
* @return mixed | |
*/ | |
var getInnerValue = function(obj, ns) { | |
if(typeof obj === 'object' && ns.length) return getInnerValue(obj[ns.shift()], ns); | |
return obj; | |
}; | |
/* | |
* Put the data in place | |
* | |
* Takes a selector to look into and a data object | |
* | |
* @param string Selector string | |
* @param object Data object | |
*/ | |
var initTemplate = function(selector, data) { | |
var elms = document.querySelectorAll(selector), | |
regex = /\{\{\s+?([a-zA-Z0-9\.]+)\s+?\}\}/g; | |
[].forEach.call(elms, function(element) { | |
element.innerHTML = element.innerHTML.replace(regex, function(match, p1) { | |
return getInnerValue(data, p1.split('.')); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment