dominik dominik - 23 days ago 10x
Java Question

Thymeleaf: replace newline characters with <br>

I have a field (

<textarea name="desc" />
) that may contain newlines and I want to replace them with their HTML counterpart:
<br />
. How can I do this? I'm using Thymeleaf 2.1.4.RELEASE.


As in JSP, it's not possible to use simple and straightforward

${#strings.replace(desc, '\n', '<br />')}

There are at least two problems:

  • '\n' is treated by underlying expression language (SpEL in my case as I'm using Spring MVC) as string literal that consist of two separate characters: '\' and 'n' rather than single newline character
  • exception is being thrown as the Thymeleaf underlying XML parser does not allow to put < and > inside expressions

The solution I found for the first problem is to set newline character in a controller and pass it to view.

To address the second problem you need to use &lt; instead of < and &gt; instead of >. Also remember that this implies using th:utext instead of th:text

// in controller:
model.addAttribute("newLineChar", '\n');

// in view
${#strings.replace(desc, newLineChar, '&lt;br /&gt;')}

If you are using Thymeleaf + Spring (what means that Thymeleaf will use SpEL instead of OGNL), you may also use SpEL T operator.This way you don't have to declare the newline variable in your controller but mind out that newline separator in this case will vary across operating systems that your app is running on:

${#strings.replace(desc, T(System).getProperty('line.separator'), '&lt;br /&gt;')}

What I'm going to finally use is the combination of the above + Apache StringUtils that defines public static final String LF = "\n";:

${#strings.replace(desc, T(org.apache.commons.lang3.StringUtils).LF, '&lt;br /&gt;')}