java - 如何在 Thymeleaf 中静态初始化 Map?

标签 java thymeleaf

我有以下thymeleaf导航栏 html,并希望通过使用 th:each 重复创建链接来缩短它来自静态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>

问题是:如何初始化静态 Map在 html 页面内,无需绑定(bind)到后端 Controller ?该映射应该键值代表“url 路径”和“链接名称”之间的映射。

在 Java 代码中,这将是:

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

但是我怎样才能在没有后端代码的情况下用普通的 thymeleaf html 实现这一点呢?

类似于:

<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 。 (括号之间的空格 - ${ { - 很重要,否则表达式将使用 thymeleaf 双括号语法进行解释。)

<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>

关于java - 如何在 Thymeleaf 中静态初始化 Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45637439/

相关文章:

spring-mvc - 在 Thymeleaf 的下拉列表中使用 HashMap

java - Spring 安全和 Thymeleaf 不起作用

spring - org.springframework.expression.spel.SpelEvaluationException - 无法在 null 上找到属性或字段

java - 从数据库中检索一些特定的表

java - 如果 Java 中的 'Download as zip' 双字节文件名被破坏

java - 删除父节点并保留其子节点

java - 获取/设置非静态字符串为静态字符串以通过Java传递

java - Apache Commonfs VFS 避免增加临时目录

Spring - 无法解析 MVC "view"thymeleaf

spring-boot - Thymeleaf 模板未在 if 条件内渲染参数值