Thymeleaf: Best Way to Display Active Navigation Item

This tutorial is about how to highlight the currently active page in your navigation with Thymeleaf and Spring Boot. Highlighting the active page is a known usability pattern and should help users to find their way around your web application.

Consider this example:

In the navigation above, the navigation item “Cronjob Monitoring” is highlighted.

The menu is generated with this Thymeleaf code:

<nav class="mdl-navigation">
    <a th:classappend="${#request.requestURI.startsWith(navItem.getLink()) ? 'mdl-navigation__link-active':''}" th:each="navItem: ${navigation}" th:id="${navItem.getIdentifier()}" class="mdl-navigation__link"
        th:href="@{${navItem.getLink()}}" th:text="${navItem.getName()}"></a>
</nav>

By using th:each, a link is generated for each navigation entry.

th:classappend is used to conditionally append a CSS class to the <a> element. The class mdl-navigation__link-active in this case simply changes the background color, but you can opt for a less subtle approach.

request.requestURI.startsWith(navItem.getLink()) evaluates to true if the specific navigation item’s URL is currently opened in the user’s web browser. For example:

If https://app.pingmy.tech/dashboard is the result of navigation item’s getLink(), an active URL of https://app.pingmy.tech/dashboard/ will evaluate to true, but so will https://app.pingmy.tech/dashboard/stats or any other subpath.

This method is very powerful because as long as you add all your controller actions with the same prefix, your navigation works out of the box without having to set any variables in the controller methods.

The accompanying CSS may look like this:

.mdl-navigation__link {
    color: #ffffff;
    font-weight: normal;
}

.mdl-navigation__link:hover{
    background-color:#333;
}

.mdl-navigation__link-active {
    font-weight: bold;
    background-color: #554477;
}

Interested in monitoring your background tasks?

https://www.pingmy.tech/ is currently launching as a public beta – it is a new web app which helps you monitoring your periodic background tasks (such as backups, data exports, accounting checks etc) and notifies you via email or slack when your services appear unavailable. Check it out – it is completely free.

Thymeleaf: Output Size of List

Question: In my Thymeleaf template, I want to output the size of a list of objects. For example, for the list

List<String> list = Arrays.asList("Go", "Python", "Scala");

the result should be 3. How is this possible using just Thymeleaf syntax?

You can use the following expression:

<span th:text="${#lists.size(myList)}">[Number of Elements]</span>

And just in case you want to check if the list is empty, there is also an easy method for that:

<span th:if="${#lists.isEmpty(myList)}">This list is empty</span>