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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.