handlebars.jsclient-side-templating

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


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?


Solution

  • 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>