Answer the question
In order to leave comments, you need to log in
How to substitute a class in Thymeleaf?
Application on Spring Boot. Thymeleaf template engine
There is a url in the controller, by which the html page appears.
There is a menu with links on the page. The menu is the same on each page, except that the color of the active link changes. In order not to create a menu on the page every time, I made a fragment, and I already use it on every page.
The problem is that the links on the page are dynamic. When the link hits the current page, its color changes, thereby showing which page the user is on.
How can I add class with color for clickable link in css according to url?
controller:
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("condition", "link-active");
return "home";
}
}
<!-- NAVIGATION MENU-->
<div th:replace="fragments/navbar :: navbar">
</div>
<div th:fragment="navbar">
<header class="header">
<a class="header-logo" href="#" th:href="@{/}"><img src="/images/logo.png" alt="">
</a>
<ul class="header-links">
<li><a th:href="@{/}">Home</a></li>
<li><a href="#" class="link-item">Get Library<i class="fab fa-github"></i></a></li>
<li><a href="#" class="link-item">Examples</a></li>
<li><a href="#" class="link-item">Tutorials</a></li>
</ul>
</header>
</div>
Answer the question
In order to leave comments, you need to log in
Hello!
You can do this at the thymeleaf level.
Something like this should work:
<li><a href="#" class="link-item" th:classapend="${#strings.contains(#httpServletRequest.requestURI, '/tutorials')} ? colorClass : baseClass">Tutorials</a></li>
th:class
&th:classappend
So far I found this solution:
Added another url for redirect in the controller:
@GetMapping("/home")
public String home() {
return "home";
}
@GetMapping("/")
public String homePage() {
return "forward:/home";
}
<ul class="header-links">
<li th:class="${#httpServletRequest.requestURI.contains('/home')} ? 'link-active' : 'link-inactive'"><a th:href="@{/home}">Home</a></li>
<li><a href="https://github.com/tttapa/Control-Surface" target="_blank">Get Library<i class="fab fa-github"></i></a></li>
<li th:class="${#httpServletRequest.requestURI.contains('/examples')} ? 'link-active' : 'link-inactive'"><a th:href="@{/examples}">Sketch Examples</a></li>
<li th:class="${#httpServletRequest.requestURI.contains('/tutorials')} ? 'link-active' : 'link-inactive'"><a th:href="@{/tutorials}">Video Tutorials</a></li>
</ul>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question