Last active
January 18, 2016 07:21
-
-
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
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 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