-
-
Save cliffordfajardo/ab44544e1c5181257b53 to your computer and use it in GitHub Desktop.
HTML escaping and templating; From here: https://github.com/Daniel-Hug/webApp/blob/531397cfa26ca1a89e07fe00ae84673e4004ee75/js/app-base.js
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
// Make strings safe for innerHTML and attribute insertion (templates): | |
var escapeHTML = (function() { | |
var entityMap = { | |
'&': '&', | |
'<': '<', | |
'>': '>', | |
'"': '"', | |
"'": ''' | |
}, | |
re = /[&<>"']/g; | |
return function(str) { | |
return String(str).replace(re, function (char) { | |
return entityMap[char]; | |
}); | |
}; | |
})(); | |
// Templating: | |
var tmp = {}; | |
(function(regExp) { | |
function evalDots(obj, key) { | |
var keys = key.split('.'); | |
var nextObj; | |
return keys.length ? | |
(nextObj = obj[keys[0]], (keys.length > 1 ? | |
(keys.shift(), evalDots(nextObj, keys.join('.'))) : | |
nextObj)) : | |
obj; | |
} | |
[].forEach.call(document.querySelectorAll('script[type="text/tmp"]'), function(el) { | |
var src = el.innerHTML; | |
tmp[el.id] = function(data) { | |
var newSrc = src.replace(regExp, function(match, key) { | |
var numCurlyBraces = match.length - key.length; | |
return numCurlyBraces % 2 ? match : | |
(numCurlyBraces === 6 ? evalDots(data, key) : escapeHTML(evalDots(data, key))); | |
}); | |
return newSrc; | |
}; | |
}); | |
})(/{{{?([\w.]+)}}}?/g); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment