Skip to content

Instantly share code, notes, and snippets.

@Daniel-Hug
Last active January 18, 2016 07:21
Show Gist options
  • Save Daniel-Hug/de430105b62c390228e4 to your computer and use it in GitHub Desktop.
Save Daniel-Hug/de430105b62c390228e4 to your computer and use it in GitHub Desktop.
HTML escaping and templating; Demo: http://jsbin.com/bahimu/edit?html,js,output
// Make strings safe for innerHTML and attribute insertion (templates):
var escapeHTML = (function() {
var entityMap = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
},
re = /[&<>"']/g;
return function(str) {
return String(str).replace(re, function (char) {
return entityMap[char];
});
};
})();
// Templating:
var template = {};
(function(regExp) {
// get the value of passed keys when chained on obj:
// getVal(document, ['body', 'parentNode', 'children', 'length']);
// => 2
function getVal(obj, keys) {
if (keys.length) {
var nextObj = obj[keys[0]];
return keys.length > 1 ?
getVal(nextObj, keys.slice(1)) :
nextObj;
} else {
return obj;
}
}
var templateScripts = document.querySelectorAll('script[data-template]');
[].forEach.call(templateScripts, function(el) {
var src = el.innerHTML;
template[el.dataset.template] = function(data) {
var newSrc = src.replace(regExp, function(match, key) {
var numCurlyBraces = match.length - key.length;
var keyChain = key.split('.');
return numCurlyBraces % 2 ? match :
numCurlyBraces === 6 ? getVal(data, keyChain) :
escapeHTML(getVal(data, keyChain));
});
return newSrc;
};
});
})(/{{{?([\w.]+)}}}?/g);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment