Bootstrap Navbar Highlighting in Thymeleaf

Here’s a quick guide to highlighting your Bootstrap navigation bar tabs in Thymeleaf. There are several ways of doing this, but here is one that’s pretty straightforward and keeps the logic strictly in Thymeleaf. You’ll find the source in my Spring Data MVC Thymeleaf app on Github, in branch v0.1.4.

We’re highlighting the “Contacts” navbar tab here.

We’re using Standard Thymeleaf Layout with Spring MVC. Here’s the above Thymeleaf page HTML calling various fragments. Notice the navbar fragment statement.

th:replace=fragments/navbar :: navbar('contacts')

Now where the action happens in the navbar fragment. Notice the “activeTab” parameter passed to the fragment in

<div th:fragment="navbar(activeTab)">

We use that to dynamically set the class on each <li /> Thymeleaf class element to set the “active” class, as in

<li th:class'"${activeTab == 'contacts'}? 'active' : null">

With the resulting HTML, where our “contacts” tab is highlighted by the class=”active” assignment.