'Thymeleaf + Spring : How to keep line break?

I'm using Thymeleaf template engine with spring and I'd like to display text stored throught a multiline textarea.

In my database multiline string are store with "\n" like this : "Test1\nTest2\n...."

With th:text i've got : "Test1 Test2" with no line break.

How I can display line break using Thymeleaf and avoid manually "\n" replacing with < br/> and then avoid using th:utext (this open form to xss injection) ?

Thanks !



Solution 1:[1]

Try putting style="white-space: pre-line" on the element.

For example:

<span style="white-space: pre-line" th:text="${text}"></span>

You might also be interested in white-space: pre-wrap which also maintains consecutive spaces in addition to line breaks.

Avoid using th:utext if possible as it has serious security implications. If care is not taken, th:utext can create the possibility of XSS attacks.

Solution 2:[2]

Maybe not what the OP had in mind, but this works and prevents code injection:

<p data-th-utext="${#strings.replace(#strings.escapeXml(text),'&#10;','&lt;br&gt;')}"></p>

(Using HTML5-style Thymeleaf.)

Solution 3:[3]

In my case escapeJava() returns unicode values for cyrillic symbols, so I wrap all in unescapeJava() method help to solve my problem.

<div class="text" th:utext="${#strings.unescapeJava(#strings.replace(#strings.escapeJava(comment.text),'\n','&lt;br /&gt;'))}"></div>

Solution 4:[4]

If you are using jQuery in thymleaf, you can format your code using this:

$('#idyourdiv').val().replace(/\n\r?/g, '<br />')

Hope that answer can help you

Solution 5:[5]

Try this

<p th:utext="${#strings.replace(#strings.escapeJava(description),'\n','&lt;br /&gt;')}" ></p>

Solution 6:[6]

You need to use th:utext and append break line to string. My code is:

StringBuilder message = new StringBuilder();
        message.append("some text");
        message.append("<br>");
        message.append("some text");

<span th:utext="${message}"></span>

Solution 7:[7]

Inspired by @DavidRoberts answer, I made a Thymeleaf dialect that makes it easy to keep the line breaks, if the css white-space property isn't an option. It also bring support for BBCode if you want it. You can either import it as a dependency (it's very light, and very easy to set up thanks to the starter project) or just use it as inspiration to make your own. Check it out here : https://github.com/oxayotl/meikik-project

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 holmis83
Solution 3 npace
Solution 4 marc_s
Solution 5 K. Siva Prasad Reddy
Solution 6 Stefan Dosković
Solution 7 Jean Alexandre