Search code examples
javaspring-bootthymeleaf

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


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.


Solution

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