cliffordfajardo
1/18/2016 - 3:08 AM

HTML escaping and templating; From here: https://github.com/Daniel-Hug/webApp/blob/531397cfa26ca1a89e07fe00ae84673e4004ee75/js/app-base.js

// 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 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);