1. Introduction

In this tutorial, we will learn how to use Thymeleaf to serve web content in a Spring Boot application. We will learn how to display different type of content from properties files and model attributes.

2. Display content from Message Properties File

Thymeleaf provides th:text=”#{property}” tag to display property values from message property files. Let’s create a message under messages.properties file:

Message = Message loaded from messager.properties!

Let’s see a sample tag for showing message from a properties file:

<span th:text="#{Message}"></span>

3. Display Model Attributes

3.1. Simple Attributes

We can use th:text=”${attributename}” tag to display the model attribute values. Let’s add a model attribute in the Spring Controller class:

model.addAttribute("name", name);

Let’s see the Thymeleaf tag for showing the name model attribute:

<span th:text="${name}"></span>

3.2. Collection Attributes

We can use th:each=”item: ${item-list}” to iterate over a collection. Let’s create a model attribute with a list of items.

List<String> names = new ArrayList<>();
// logic to add names
model.addAttribute("names", names);

Next, we need to define the Thymeleaf tag to iterate over items:

<li th:each="name: ${names}">
    <span th:text="${name}"></span>
</li>

4. Conclusion

In this article, we learned how to run Thymeleaf under Spring Boot. We also saw some basic usage by displaying content from message properties and model attributes.

The full working source can be found over on GitHub.

Display Web Content using Thymeleaf
Tagged on:     

Satish Pandey

I am an expert Java Spring Angular developer with 10+ years of rich and varied experience in developing end-to-end Web Applications. I maintain this blog and publish articles in my free time to help the community. Email: satish@cloudtechpro.com

Leave a Reply

avatar
1024
  Subscribe  
Notify of