Does handlebars.js replace newline characters with <br>?

Uri picture Uri · Sep 8, 2012 · Viewed 27.5k times · Source

Trying to use handlebars.js for templating but the library seems to ignore newlines.

What is the correct way to deal with newlines? Should they be replaced manually after the templating action?

Answer

Uri picture Uri · Sep 13, 2012

It doesn't do so automatically, but using the helpers feature this can be achieved:

JS:

Handlebars.registerHelper('breaklines', function(text) {
    text = Handlebars.Utils.escapeExpression(text);
    text = text.replace(/(\r\n|\n|\r)/gm, '<br>');
    return new Handlebars.SafeString(text);
});

HTML template:

<div>
    {{breaklines description}}
</div>