Last active
March 11, 2016 20:33
-
-
Save dan-f/1d3436d048454abf5fa8 to your computer and use it in GitHub Desktop.
Utilities for escaping and interpolating HTML strings in 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
// Requires underscore.js | |
var HTML, | |
Html; | |
HTML = function HTML (string) { | |
this.string = string; | |
}; | |
HTML.prototype.toString = function toString() { | |
return this.string.toString(); | |
} | |
Html = function Html(string, options) { | |
if (!_.isString(string) && !(string instanceof HTML)) { | |
throw new Error('Expected a string'); | |
} | |
if (!_.isObject(options) && typeof options !== 'undefined') { | |
throw new Error('If provided, options must be an object'); | |
} | |
if (_.isUndefined(options)) { | |
return new HTML(string); | |
} else { | |
return new HTML(string.replace(/{\w+}/g, function (parameter) { | |
var substitution = options[parameter.slice(1,-1)]; | |
if (substitution instanceof HTML) { | |
return substitution; | |
} else { | |
return _.escape(substitution); | |
} | |
})); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment