Created
May 6, 2014 18:26
-
-
Save sylvaindethier/a5f7435af4eda9e9b474 to your computer and use it in GitHub Desktop.
Handlebars helper new line to br
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
/** | |
* Replace \n by <br />, such as the `nl2br` in PHP | |
* @see http://stackoverflow.com/questions/2919337/jquery-convert-line-breaks-to-br-nl2br-equivalent | |
*/ | |
Handlebars.registerHelper('nl2br', function (text, isXhtml) { | |
var breakTag = (isXhtml || typeof isXhtml === 'undefined') ? '<br />' : '<br>'; | |
return (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); | |
}); |
this version reuses the internals from Handlebars in accordance with the docs:
Handlebars.registerHelper('nl2br', function(text, isXhtml) {
const breakTag = isXhtml ? '<br />' : '<br>'
const withBr = Handlebars.escapeExpression(text).replace(
/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,
'$1' + breakTag + '$2'
)
return new Handlebars.SafeString(withBr)
})
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a handlebars each new line plugin
https://gist.github.com/dhollenbeck/c4cde67aee08a3db06edf34c02ddd543