Best way to convert newlines in data to HTML BR elements?


#1

Hi, all.

I’m trying to figure out the best way to get Ember.js to convert special characters to properly formatted HTML. In this case, I have data that contains newlines that I’d like Ember.js/Handlebars to display as BR elements.

Following this example (search for “breaklines”), I’ve gotten this to work, but I want to be sure I’m not overlooking some built-in functionality that does the same thing.

TIA.


#2

I’d implement this as a helper.

Ember.Handlebars.registerBoundHelper('expandLineBreaks', function (text) {
    return new Ember.Handlebars.SafeString(text.replace(/\n/g, '<br>'));
});

#3

Depending on how scrubbed the data is you could also turn this into a computed property.

Example: http://jsfiddle.net/NQKvy/1452/

Edit: remove the triple curly and XSS warning in favor of safestring


#4

P.S. if this is some user inputted text for which you are worried about XSS (and therefore don’t want to use handlebars’s safestring feature), you can get new lines to display using CSS.