Labs ICT
Pro Login

Text Replacement

th:text and th:utext for dynamic content.

Text Replacement

Replacing text is the most common thing you'll do in Thymeleaf. Let's look at how to display data, handle HTML safely, and combine text.

th:text

The th:text attribute replaces the inner HTML of an element with the value of an expression. It escapes HTML characters by default to prevent XSS attacks.


<p th:text="${userMessage}">Default message</p>
    

If userMessage is "Hello <b>World</b>", the output will show the angle brackets literally, not as bold text. That's the safety feature at work.

th:utext for Unescaped HTML

Sometimes you actually want to render HTML. Use th:utext (unescaped text) for that. Be careful — only use it with content you trust.


<p th:utext="${safeHtml}">HTML content here</p>
    

Now if safeHtml contains "Hello <b>World</b>", the browser will render "Hello" in bold. Use th:utext wisely.

Template Literals

Need to combine text with variables? Use the pipe syntax. It's cleaner than string concatenation.


<p th:text="|Hello, ${name}! Welcome to our site.|"></p>
<p th:text="|You have ${count} new messages.|"></p>
    

The |...| syntax lets you mix static text and expressions without messy quotes. It's one of Thymeleaf's nicest features.

Try it Yourself →

Text Concatenation

You can also use the + operator to combine strings, though the pipe syntax is usually cleaner.


<p th:text="'Hello, ' + ${name} + '!'></p>
<p th:text="'Total: $' + ${price}"></p>
    

Notice the single quotes around static text. That's required in Thymeleaf expressions. Without them, Thymeleaf treats the text as a variable name.