Search code examples
javahtmlthymeleaf

Thymeleaf ignores "\n" in String returned from method


In my HTML I'm using paragraph that gets content by calling method via thymeleaf:

<p data-th-text="${fund.formatDescription()}"></p>

Method:

private String description;

public String formatDescription() {  
    return description.replace(";", " \n ");
}

I want my description to have end lines in palce of every semicolon. So that's why I added \n. But thymeleaf ingores new lines and returns continuous text. I tried adding <br/> but it ends up not interpreted as html. What should I add in place of semicolon to force new line in the description?


Solution

  • Html ignores newlines (this isn't thymeleaf's fault). You can either:

    • Put the description into <pre></pre> tags (or use the css white-space property on the <p> element).
    • Instead of replacing ; with \n, replace it with <br /> and use th:utext instead of data-th-text. (This means that html will be unescaped, so you better make sure users can't put other html into the description field or you open yourself up to html attacks).