Search code examples
javahtmlspring-mvcspring-bootthymeleaf

How to ignore HTML tags using Thymeleaf when printing text string?


I'm using Thymeleaf in my Spring Boot project.

I've got a text string which contains some HTML tags and my goal is to print it without styling as well as without any HTML tags.

Using:

<p th:text="${myString}"> </p>

I've got something like this:

<b> text </b>

And that's ok because the value of myString text string is

String myString = "<b> text </b>"; 

So trying to do it in other way, using:

<p th:utext="${myString}"> </p>

I've got something like this:

text

But my goal ist to get non-formatted plain text like this:

text 

Simply text without any HTML tags and without rendering the HTML code.

How can I acheive this with using Thymeleaf only?

I've tried some th:remove="tags" along with th:inline="text" but It doesn't work so far.

Thanks in advance


Solution

  • Thymeleaf doesn't have any native support for this, so you're going to have to find your favorite library for removing tags use it instead. In this example, I used Jsoup.

    After adding it to your pom file, something like this should work:

    <div th:text="${T(org.jsoup.Jsoup).parse(myString).text()}" />
    

    You could also create your own dialect that does it automatically, but that's more complicated. Then you could use your own attributes:

    <div bohdan::removehtml="${myString}" />