简体   繁体   中英

Handlbars and HTML

I have a database entry with the following data:

"text": "Paragraph 1\n\nParagraph 2\n\nParagraph 3\n"

However when I render this in handlebars as follows:

<div>{{{text}}}</div>

I get:

Paragraph 1 Paragraph 2 Paragraph 3

But I am expecting:

Paragraph 1
Paragraph 2
Paragraph 3

Is anyone able to help explain what is going on?

您可以使用<br>替换\\n ,如下所示:

text.replace(/\n/g, "<br>");

HTML elements do not preserve the line breaks, you need to use <br> instead, however you can use <pre>

The HTML <pre> element defines preformatted text. It preserves both spaces and line breaks.

additionally, since you are using handlebars, you can define a helper:

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 text}}
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM