0

On the backend side, I am getting a text, for e.g:

"first line ↵ second line ↵ third line"

and in the HTML I would like this text to be displayed like

first line
second line
third line

this is my html code:

<ul>
    <li th:text="${myVar}">#</li>
</ul>

and I can see al the text in a single line, with the '↵' unicode char omitted. And I have the same behaviour with the th:utext attribute, what would be the solution? Maybe it needs any type of preprocessing on the backend, and send another formatted string to the template?

Thanks!

John P
  • 1,159
  • 2
  • 18
  • 44
  • 1
    This is not a Thymeleaf problem, it's an HTML problem. HTML doesn't display newlines. There any ways to change this with css, see this: https://stackoverflow.com/questions/9492249/render-a-string-in-html-and-preserve-spaces-and-linebreaks – Metroids Jul 18 '23 at 14:50
  • this was also my solution – John P Jul 19 '23 at 07:52

2 Answers2

0

Simply replace linebreaks with <br> in your text before storing in your database. And th:utext=${myVar} in the html element will not escaping your text. Be cautious with that kind of permissiveness to fight XSS attacks against your webapp.

BendaThierry.com
  • 2,080
  • 1
  • 15
  • 17
  • 1
    thanks! this is what I was testing now, but I would like a more safe solution, as it is a user input, and I wouldn't like to allow users to send me html – John P Jul 18 '23 at 10:12
  • I am afraid you will not find a more safe solution if you want|need to preserve the original user input as it is. Usual WYSIWYG editors have some bunch of options to handle a safer way to change user input as safe strings. Html encoding on the fly for special chars could be a way for some things. – BendaThierry.com Jul 18 '23 at 10:18
0

The solution I found was

  1. on the backend, replace ↵ with a '\n'

  2. use css in the html to process the \n as a new line

    <span style="white-space: pre-line" th:text="${text}">#</span>
    
John P
  • 1,159
  • 2
  • 18
  • 44