Search code examples
spring-bootspring-mvcthymeleafconditional-operator

Thymeleaf multiple ternary operator with OR condition


With Thymeleaf I am using this (it works fine):

<li class="drop-down" th:classappend="${#httpServletRequest.getRequestURI() == '/url1' ? 'active':''}"><a href="#">MainMenu</a>
<ul>
<li><a href="/url1" th:href="@{/url1}"><i
class="fas fa-users"></i> url1</a></li>
<li><a href="/url2" th:href="@{/url2}"><i
class="fas fa-users"></i> url2</a></li>
<li><a href="/url3" th:href="@{/url3}"><i
class="far fa-file-alt mr-1"></i> url3</a></li>
<li><a href="/url4" th:href="@{/url4}"><i
class="fas fa-sign-out-alt mr-1"></i>url4</a></li>
</ul></li>

Now I want to set the active class to the main menu if any of the URL 1/2/3/4 is clicked. So I tried this (And it did NOT work):

<li class="drop-down" th:classappend="${#httpServletRequest.getRequestURI() == '/url1' ? 'active':'' :: '/url2' ? 'active':'' :: '/url3' ? 'active':'' :: '/url4' ? 'active':'' }"

Also I tried a lot other combination with "or" and "||", nothing worked. All these URLs (context paths) are totally different and I CAN NOT use like - contains. I am sure I am missing the idea, but need some help here. Kindly suggest.


Solution

  • It seems you want to append the active class when request URI matches any from a set of fixed values. So you can write your <li> element like this:

    <li
       class="drop-down"
       th:with="urls=${new String[]{'/url1','/url2','/url3','/url4'}}"
       th:classappend="${#arrays.contains(urls, #httpServletRequest.getRequestURI()) ? 'active' : ''}">
    

    ...where:

    • th:with declares an array named urls containing urls which triggers appending of a class.
    • th:classappend checks whether the urls array contains a value returned by #httpServletRequest.getRequestURI() and conditionally appends a class.