Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to static initialize a Map in Thymeleaf?

Tags:

java

thymeleaf

I have the following thymeleaf navigation bar html, and would like to shorten it by repeating the link creation with th:each from a static Map:

<div id="navbar" class="collapse navbar-collapse">
    <ul class="nav navbar-nav">
        <li th:classappend="${#httpServletRequest.getRequestURI() == '/home' ? 'active':''}">
            <a href="/home">Home</a></li>
        <li th:classappend="${#httpServletRequest.getRequestURI() == '/pax' ? 'active':''}">
            <a href="/pax">Person</a></li>
        <li th:classappend="${#httpServletRequest.getRequestURI() == '/about' ? 'active':''}">
            <a href="/about">About</a></li>
    </ul>
</div>

The question is: how can I initialize a static Map inside the html page, without having to bind to a backend controller? The map should key-value represent the mapping between "url path" and "link name".

In java code this would be:

new HashMap<String, String>() {{
   put("/pax", "Person");
}};

But how can I achieve this in plain thymeleaf html, without backend code?

Similar to:

<li th:each="entry : ${HOW TO HASHMAP}"
    th:classappend="${#httpServletRequest.getRequestURI() == '/'+entry.getKey()' ? 'active':''}">
  <a th:href="'/'+${link.getKey()}" th:text="$entry.getValue()"/>
</li>
like image 882
membersound Avatar asked May 02 '26 02:05

membersound


1 Answers

Spring expression inline maps. (Spaces between brackets -- ${ { -- are important, otherwise the expression is interpreted using thymeleaf double bracket syntax.)

<li th:each="entry: ${ {home:'Home', pax:'Person', about:'About'} }"
    th:classappend="${#httpServletRequest.getRequestURI() == '/' + entry.key ? 'active' : ''}">
  <a th:href="'/' + ${entry.key}" th:text="${entry.value}"/>
</li>
like image 129
Metroids Avatar answered May 03 '26 16:05

Metroids



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!