Displaying active navigation based on contextual data

You can do this:

<ul class="nav navbar-nav">
    <li th:classappend="${#httpServletRequest.getRequestURI() == '/dashboard' ? 'active':''}"><a th:href="@{/dashboard}"><span>Dashboard</span></a></li>
    <li th:classappend="${#httpServletRequest.getRequestURI() == '/orders' ? 'active':''}"><a th:href="@{/orders}"><span>Orders</span></a></li>
    <li th:classappend="${#httpServletRequest.getRequestURI() == '/income' ? 'active':''}"><a th:href="@{/income}"><span>Income</span></a></li>
    <li role="separator" ></li>
</ul>

You could add a ModelAttribute with the value active in your controllers for each page, e.g. :

SettingsController.java

@RequestMapping("/settings")
public String viewSettings(Model model) {
  // do stuff
  model.addAttribute("classActiveSettings","active");
  return "settings";
}

OR in a SettingsControllerAdvice.java

@ControllerAdvice(assignableTypes = SettingsController.class)
public class SettingsControllerAdvice {

    @ModelAttribute("classActiveSettings")
    public String cssActivePage() {
        return "active";
    }

}

Then, in the navigation fragment included in your settings.html :

<ul class="nav nav-tabs">
     <!-- Other links -->
    <li role="presentation" th:class="${classActiveSettings}">
       <a th:href="@{/settings}">Settings</a>
    </li>
</ul>

Finally, you can repeat this process for each controller and links in your navbar.


while this is an old question, I want to share this solution as it could be much more elegant!

http://nixmash.com/post/bootstrap-navbar-highlighting-in-thymeleaf

  • Add a parameter (activeTab) to the navigation fragment.
<div th:fragment="common-navbar(activeTab='activeTab')"></div>
  • pass the value of it in the main pages that use the navbar fragment
 <div th:replace="common/navbar :: common-navbar(about)"></div>
  • check for it in the 'li' element to set the 'active' class
 <li th:class="${activeTab == 'about'}? 'active' : null"><a href="">About</a></li>

Although i think it is ugly solution and it is pity that thymeleaf does not have some macros for it, you can use:

<li th:classappend="${#httpServletRequest.getRequestURI().startsWith('/hotels') ? 'active':''}">
    Hotel
</li>

It will work also for "deeper" links like /hotels/new so it is usable also for multilevel menus.