Created
March 19, 2015 13:10
-
-
Save iStefo/61b87ea78a978c90b599 to your computer and use it in GitHub Desktop.
Handlebars escapeExpression for Spacebars
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
/* | |
escapeExpression inserted into the Spacebars namespace, taken from | |
https://github.com/wycats/handlebars.js/blob/master/lib/handlebars/utils.js | |
*/ | |
var escape = { | |
"&": "&", | |
"<": "<", | |
">": ">", | |
'"': """, | |
"'": "'", | |
"`": "`" | |
}; | |
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