2

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?

Michael Dz
  • 3,655
  • 8
  • 40
  • 74

2 Answers2

6

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).
Metroids
  • 18,999
  • 4
  • 41
  • 52
  • Still the same result, I can see on website `
    ` as normal text. I've tried with `data-th-utext` but still tags are not interpreted as HTML.
    – Michael Dz May 15 '17 at 20:07
  • @MichaelDz -- I verified this works before posting my answer, and you can see the documentation for utext [here](http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#more-on-texts-and-variables)... can you verify your replace? What does the html look like when you view-source? – Metroids May 15 '17 at 20:20
  • That's how HTML source looks like `

    text
    text
    text

    , I've used `data-th-utext` in my paragraph, `
    ` tag doesn't help either.
    – Michael Dz May 16 '17 at 11:21
  • @MichaelDz -- think you've got something else going on. It would look like `

    test <br /> test <br /> final

    ` if utext were not working.
    – Metroids May 16 '17 at 14:23
  • 2
    for some reason `data-th-utext` is not working with HTML tags. But instead I've replaced it with `th:utext` and now it is working fine! Thank you for help, add this to your answer so I can mark it as accepted. – Michael Dz May 16 '17 at 14:42
  • " with \n, replace it with
    and use th:utext instead of data-th-text", works perfectly for me, thank you so much for both of you. Cheers !!!
    – JonathanLu Feb 26 '21 at 20:30
1

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) or just use it as inspiration to make your own. Check it out here : https://github.com/oxayotl/meikik-project