Thymeleaf, how to do a new paragraph with a string of text

Viewed 875

In my Java program, I have a populator with a string that is 2 paragraphs long.

String myString = "Paragraph 1 text... \n" +
                    "\n" +
                    "Paragraph 2 text...";

When I display it using Thymeleaf, it displays as 1 paragraph.

"Paragraph 1 text... Paragraph 2 text..."

How do I separate them into paragraphs like so:

"Paragraph 1 text...

Paragraph 2 text..."

Here's the Thymeleaf to display the text:

        <section class="post-content" th:text="${post.myString}">
        </section>

EDIT: I have tried using tags (like <p> and <br />) but they get displayed as text and not as html tags.

2 Answers

Use the <br> tag to create a line break to display on the front end, instead of "\n".

String myString = "Paragraph 1 text... <br/>" +
                    "<br/>" +
                    "Paragraph 2 text...";

You can use th:utext to display the HTML without escaping.

<section class="post-content" th:utext="${post.myString}">
</section>

You can of course insert html and use th:utext.

// Java
String myString = "Paragraph 1 text... <br /><br />Paragraph 2 text...";

<!-- HTML -->
<section class="post-content" th:utext="${post.myString}" />

(When possible, I would avoid this because it's more open to abuse -- the html in this variable could cause your page to display incorrectly, or there could be scripts injected -- I would never use th:utext with untrusted user input for example.)

You can also choose to display newlines with css. For example:

// Java
String myString = "Paragraph 1 text... \n\nParagraph 2 text...";

<!-- HTML -->
<section class="post-content" style="white-space: pre-line;" th:text="${post.myString}" />
Related