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?
You can do this:
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
For those using Thymeleaf 3:
If you have a context path on your application:
Edit:
To be concise:
The benefit to using
request.getServletPath()
is that it ignores the context path, if there is one.You could add a ModelAttribute with the value active in your controllers for each page, e.g. :
SettingsController.java
OR in a SettingsControllerAdvice.java
Then, in the navigation fragment included in your settings.html :
Finally, you can repeat this process for each controller and links in your navbar.
Although i think it is ugly solution and it is pity that thymeleaf does not have some macros for it, you can use:
It will work also for "deeper" links like /hotels/new so it is usable also for multilevel menus.
May be this code would be helpful for someone. Attention! It's not Thymeleaf solution, just js code which you can add on your pages.