Micronaut | Use Thymeleaf for dynamic templating

Photo by Anja Junghans on Unsplash

What is Thymeleaf?

Thymeleaf is a dynamic templating engine for serverless applications like Micronaut or Spring. It is really useful if you want to create non static content that gets generated dynamically. Or with the words of the official website:

Configure Thymeleaf

First of all, we have to install dependencies.

implementation(“io.micronaut.views:micronaut-views-thymeleaf”)
<dependency>     
<groupId>io.micronaut.views</groupId>
<artifactId>micronaut-views-thymeleaf</artifactId>
</dependency>

Add the HTML Template files

If you want to display some HTML files, you have to put them into the location that you’ve defined in the last step. There are two types of files, index files, where the content goes in, and template files, which create the structure of the site.

Add the index.html file to src/main/resources/views

  1. I use this functionality with the th:each annotation. For each entry in entries, it will iterate through. With this, I can read out the id of the entry and the title.
  2. Right in the second line, it provides the title and the section to the layoutFile. This is really important for later use
  3. If you want to use these Thymeleaf functionalities, you also have to use the corresponding attributes.

Add the Template.html file

This file is only used to template the whole application.

Create the View

  1. The Get Annotation configures the path on which it should display the content
  2. showMenu() returns an HttpResponse.ok with a list of Entries.
  3. The data class Entries gets defined with an id and a title.

Enjoy your dynamically templated site

Developer Experience Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store