Displaying active navigation based on contextual data

I have the following separated fragment in a Thymeleaf template.

<ul class="nav nav-tabs">
    <li role="presentation"><a href="/">Freight Invoices</a></li>
    <li role="presentation"><a href="/processed">Processed Invoices</a></li>
    <li role="presentation"><a href="/postingrules">Posting Rules</a></li>
    <li role="presentation" class="active"><a href="/settings">Settings</a></li>

I want to add an "active" class to active navigation element — but it seems hard to accomplish in Thymyleaf. Any suggestions?


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

    public String viewSettings(Model model) {
      // do stuff
      return "settings";

    OR in a

    @ControllerAdvice(assignableTypes = SettingsController.class)
    public class SettingsControllerAdvice {
        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>

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