Search code examples
javaspringjspnavigationthymeleaf

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>
</ul>

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


Solution

  • 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.