Last updated: 2024-09-17
How to output text with Thymeleaf
Although Thymeleaf is well over 10 years old, it is still the most popular template language for Spring Boot. How can we display text in a Thymeleaf template that we have provided in our controller or message file?
Let's assume that in our Spring Boot project the object "name"
has already been provided by our controller. We could now display it in our template in the following two ways.
The first variant is a SpEL expression, concatenating a String with our variable. As we often already have many other attributes on our elements, the code is easier to read using expression inlining with [[ ... ]]
. We also don't have to assemble our text with a SpEL expression or introduce <span>
elements as placeholders.
Display unencoded text
Thymeleaf will encode the text for HTML by default so that any special character is displayed correctly in the browser. Sometimes, however, we want to output the text 1:1 without conversion, e.g. if our variable itself already contains HTML code. We can use the following syntax for this case - the u
in utext
stands for unformatted.
Output of text without encoding
Output of properties
If our templates are internationalized and we load all texts from a properties
file, we can fall back on the Standard Expression Syntax. Without any additional parameters, it would be simply #{app.welcome}
. However, as we also pass the name as a parameter, the whole thing then looks like this - here again including encoding.
Loading the text with a key
Our message with one parameter
Thymeleaf offers us all the necessary means to output text according to our needs. With Bootify, a Spring Boot application with Thymeleaf frontend can be created directly in the browser - while taking into account best practices for Thymeleaf and Spring Boot. The generated code includes the required setup, CRUD functions for your custom database schema and so much more.
See Pricing
or read quickstart