Skip to content

Instantly share code, notes, and snippets.

@iStefo
Created March 19, 2015 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iStefo/61b87ea78a978c90b599 to your computer and use it in GitHub Desktop.
Save iStefo/61b87ea78a978c90b599 to your computer and use it in GitHub Desktop.
Handlebars escapeExpression for Spacebars
/*
escapeExpression inserted into the Spacebars namespace, taken from
https://github.com/wycats/handlebars.js/blob/master/lib/handlebars/utils.js
*/
var escape = {
"&": "&",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#x27;",
"`": "&#x60;"
};
var badChars = /[&<>"'`]/g;
var possible = /[&<>"'`]/;
var escapeChar = function escapeChar(chr) {
return escape[chr];
};
Spacebars.escapeExpression = function escapeExpression(string) {
if (typeof string !== 'string') {
// don't escape SafeStrings, since they're already safe
if (string && string.toHTML) {
return string.toHTML();
} else if (string === null) {
return '';
} else if (!string) {
return string + '';
}
// Force a string conversion as this will be done by the append regardless and
// the regex test will do this transparently behind the scenes, causing issues if
// an object's to string has escaped characters in it.
string = '' + string;
}
if (!possible.test(string)) { return string; }
return string.replace(badChars, escapeChar);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment