How can I retrieve the current page URL with Thymeleaf?

Trying to highlight the current element in the menu using Bootstrap and the "active" class, but unsure how to retrieve the value of the current page. Below is my navigation bar:

<nav class="navbar navbar-expand-md sticky-top navbar-light bg-faded">
  <a class="nav-link waves-effect waves-light" th:href="@{/}">
    <img class="home-logo" alt="UTL-2" th:src="@{/static/img/site-logo.png}" /></a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
  <div class="collapse navbar-collapse justify-content-center" id="navbarSupportedContent">
    <ul id="myDIV" class="navbar-nav mr-auto">
      <li class="nav-item" th:classappend="${module == 'login' ? 'active' : ''}">
        <a class="nav-link waves-effect waves-light" th:href="@{/login}">Login
                        <span class="sr-only">(current)</span></a>
      </li>

      <li class="nav-item" th:classappend="${module == 'plan' ? 'active' : ''}">
        <a class="nav-link waves-effect waves-light" th:href="@{/plan}">Plan for Shipment</a>
      </li>

      <li class="nav-item" th:classappend="${module == 'orders' ? 'active' : ''}">
        <a class="nav-link waves-effect waves-light" th:href="@{/orders}">Orders</a>
      </li>

      <li class="nav-item" th:classappend="${module == 'stations' ? 'active' : ''}">
        <a class="nav-link waves-effect waves-light" th:href="@{/stations}">Stations Directory</a>
      </li>

      <li class="nav-item">
        <a class="nav-link waves-effect waves-light" th:href="@{/partner}">Partners Directory</a>
      </li>

      <li class="nav-item">
        <a class="nav-link waves-effect waves-light" th:href="@{/map}">Map</a>
      </li>

      <li class="nav-item">
        <a class="nav-link waves-effect waves-light" th:href="@{/info}">Information</a>
      </li>

      <li class="nav-item" sec:authorize="hasRole('ADMIN')">
        <a class="nav-link waves-effect waves-light" th:href="@{/admin}">Admin Panel</a>
      </li>

    </ul>

    <div id="logged-in-info">
      <span sec:authorize="isAuthenticated()">Hello, <b sec:authentication="name">(Anonimous)</b></span>
      <form sec:authorize="isAuthenticated()" method="post" th:action="@{/logout}">
        <input type="submit" class="btn btn-light" value="Logout" />
      </form>
      <form sec:authorize="isAnonymous()" method="post" th:action="@{/login}">
        <input type="submit" class="btn" value="Login" />
      </form>
    </div>
  </div>

</nav>

Attempting to use

th:classappend="${module == 'login' ? 'active' : ''}"
to apply the "active" class, but realizing that the module attribute needs to be set in the controller class for each page. Is there a way to dynamically get the name of the current active page and replace "module" with it in the code?

P.S. Have explored Javascript solutions to mark the selected element as active, but they only work until the page is refreshed since each link leads to a new page, causing the menu item to lose its "active" status.

Answer №1

If you want to implement this method, consider using httpservletrequest:

<ul id="myDIV" class="navbar-nav mr-auto">
      <li class="nav-item">
        <a th:class="${#httpServletRequest.requestURI == 'YOURPREFEREDADDRESS'} ? 'active nav-link' : 'nav-link'" th:href="@{/login}">Log in
                        <span class="sr-only">(current)</span></a>
      </li>
.
.
.
</ul>

Answer №2

If you're looking for a live demonstration, check out this link:
https://github.com/petrep/Active_navigation_highlight_Thymeleaf
The project utilizes Thymeleaf in conjunction with Spring Boot and Tomcat 9 (please note that version 10 is not compatible)
I hope this information proves to be beneficial for your needs

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The transition effect does not seem to be functioning correctly when adding a class

It seems like a common issue, but none of the solutions I've come across so far have helped. Everything appears to be standard and simple code, yet I can't seem to get it to work properly. I'm trying to create a dropdown menu where a hidden ...

Adding classes to a div in a sequential animation using jQuery: A step-by-step guide

I'm aiming to create an animated effect using jQuery that replicates the motion in this GIF. I experimented with CSS3 animation keyframes, but the result was not as clean and polished as I would like. If there is a simpler way to achieve this effect u ...

Following the addition of a row that includes select and input fields, it appears that the functionality of the select and input

After appending a div.row using dropdown selection within another div and making it sortable using the Kendo Sortable method in jQuery, the elements are loading correctly. However, the select options are not displaying, and the input field is not accepting ...

Issues arise when dealing with a CSS and HTML accordion

I decided to create a CSS and HTML collapsing menu system, also known as an accordion. I found a tutorial on how to do it here. However, I had to make some modifications because I wanted to include images in the 'sections' later on. Instead of us ...

Positioning a div with text over an image in a way that it

Hey everyone, I've run into a bit of an issue with my project. I'm trying to create a system where text appears over an image, but the problem is that my div is set to absolute position and I can't switch it to relative without causing major ...

Is there a way to display a different file, such as index.html, based on the screen width?

I'm facing an issue. I have completed a web page (with HTML, CSS, and JavaScript), but now I want to create a mobile version using different HTML files, another index.html file, and a separate CSS file. What changes do I need to make in the main page ...

Applying "Max-Height" property to the cells of a kendo

I've been struggling to figure out how to set a max-height for a tr or td element within a Kendo grid. Is it possible to set the height to 100% and restrict the max-height to 200px? The grid itself is scrollable with a height of 500px, so the scrollin ...

Starting up with card and a loop counter

Can anyone help me with getting my card bootstrapping implemented in my .html to be centered? Here is the code I'm working with: <h1> 10 Games Recommended Based on {{ selected }} </h1> <div class="container"> ...

Animation scaling on the iPhone seems to abruptly jump away once it finishes

Encountering an issue with animations that is causing unexpected behavior on physical iPhone devices but not in the simulators. The problem arises when the background zooms in and then the div suddenly jumps to the left after the animation completes, as sh ...

Is it feasible to transition a mobile webpage seamlessly without using jqm?

I'm currently developing a Phonegap app and I am trying to steer clear of jqm in my project. I find that the css is causing some issues with the html code. As a workaround, I can transition between pages using: window.location = "profiles.html"; How ...

Experience a glint in the React Suspense with React Router - Struggling with CSS properties post utilizing Suspense and Lazy

I'm experiencing an issue with my code where the CSS properties are not working properly when I wrap the code in suspense. The page loads and the suspense functions as expected, but the styling is not being applied. However, if I remove the suspense, ...

Whenever I select a link on a navigation bar, it transports me to the desired section of the page. However, I often find that the navbar ends up

Recently, I came across some website templates where clicking on a link in the navbar smoothly scrolls to the corresponding section with perfect alignment. The content at the top of the page aligns perfectly with the top of each division. Upon attempting ...

Change the background color of cells according to the value they contain

I have a scenario where I am populating a table with random numbers, and I want the background color of each cell to change based on the value of the number in that cell. Since these numbers refresh periodically, I need the colors to update accordingly as ...

"Engaging with the touchscreen inhibits the triggering of click

Within this div, I have implemented touch-action:pan-y;. Surrounding this div is an anchor tag. If you click on the div, the link will successfully redirect. However, if you swipe on the div and then click, the link won't work on the first attempt bu ...

Group in group, glitch in outdated browser

Facing an issue with IE6 while writing HTML/CSS code. I am looking to create dynamic divs using classes: Here is a simple example (not real-project code): .top {width: 50px;} .top.selected {background: #f00;} .mid {width: 114px;} .mid.selected {backgrou ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

What is the reason for the presence of "CTYPE" in my HTML upon refreshing the page?

As I am utilizing Harp and Bootstrap for my project, I am encountering a peculiar issue. Upon refreshing the page, I notice that the text ""CTYPE html>"" is inserted within the body tags. Can anyone shed light on why this is happening? ...

Trouble arises with the background of the HTML body

There seems to be a mysterious white strip appearing when I use the (google custom sesrch) search results rendering tag gcse:searchresults-only If I remove cse id from var cx or delete the above tag, everything works perfectly and the white stripe disappe ...

``Troubleshooting: Problem with Rails checkboxes and error-ridden fields

Hello there! I've encountered an interesting problem that I've traced back to using a custom bootstrap checkbox. Everything works fine, except for when I try to submit the form without checking the checkbox and receive an error message. After thi ...

How can you use ng-click to disable a div in AngularJS?

I'm looking to dynamically disable a div in AngularJS based on a certain condition. I know I can achieve this by adjusting the CSS (such as reducing contrast and color) but the div also has an ng-click property that I want to prevent from being trigge ...