Using Thymeleaf with JavaScript for Menu Highlighting

We're building an Administration Module in NixMash Spring based on the Gentelella Bootstrap Theme. When adding a User Update form I thought how nice it would be if we could control the sidebar highlighted menu in some other way than a one-to-one url match.

“Users” is highlighted on a url match of /admin/users, but we're going to use Thymeleaf to highlight selected menu items as you can see below with /admin/users/update/{userId}.

Here's the original JavaScript, where the parent of the current Url is opened with the ul.active class and the menu item with li.current-page. Pretty slick, but limited to a single Url.

Enter Thymeleaf

We begin by passing a Url path string to our Thymeleaf fragment with functions(‘/admin/users').

The currentPath parameter in our Fragment definition (1) is assigned to the JavaScript path variable with Thymeleaf Inlining (2). We change the match from an href to pathname (3) and now control which menu item is highlighted!

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.

Posted April 11, 2016 09:14 AM EDT

More Like This Post