Thymeleaf th:text Attribute

In this quick tutorial, we will take a look into Thymeleaf th:text attribute with examples.

Check out the complete Thymeleaf tutorials and examples at Thymeleaf Tutorial

Thymeleaf th:text Attribute

This attribute is responsible for displaying text that is evaluated from the expression inside it;​ 

For example: To display a message:

<h2 th:text="${message}">Hello Good Morning!.</h2>

The th:text attribute evaluates its value expression and sets the result as the body of the host tag, effectively replacing the “Hello Good Morning!” text we see in the code.

Example 1: Thymeleaf th:text Attribute with Variable Expressions

The below example demonstrates the usage of th:text attribute to evaluate variable expressions and result as the body of the <strong> tag:

    <p> Name: <strong th:text="${user.name}"></strong></p>
    <p> Email: <strong th:text="${user.email}"></strong></p>
    <p> Role: <strong th:text="${user.role}"></strong></p>
    <p> Gender: <strong th:text="${user.gender}"></strong></p>

Example 2: Thymeleaf th:text Attribute with Selection Expressions

The below example demonstrates the usage of th:text attribute to evaluate selection expressions and result as the body of the <strong> tag:

<div th:object="${user}">
    <p> Name: <strong th:text="*{name}"></strong></p>
    <p> Email: <strong th:text="*{email}"></strong></p>
    <p> Role: <strong th:text="*{role}"></strong></p>
    <p> Gender: <strong th:text="*{gender}"></strong></p>
</div>

Example 3: Thymeleaf th:text Attribute with Message Expressions

The below example demonstrates the usage of th:text attribute to evaluate message expressions and result as the body of the <strong> tag:

<h2 th:text="#{app.name}"></h2>
<h2 th:text="#{welcome.message}"></h2>

Comments