我正在使用 Java 和 Thymeleaf 构建一个应用程序,我需要将 HashMap 传递给部分应用程序。我不想从 Controller 传递它。
这是我到目前为止尝试过的:
用户.html
<div th:replace="partials/icons.html :: icons(icons=${ {name='user', title='User'}, {name='blog', title='Blog'} })"></div>
/partials/icons.html
<div th:fragment="icons">
<th:block th:each="icon : ${icons}">
<button th:class="'icon-' + ${icon.name}" th:text="${icon.title}"></button>
</th:block>
</div>
它给我一个错误,=
是意外的。正确的语法是什么?
最佳答案
编辑:我应该预先澄清:没有办法用 fragment parameters 的语法来做你想做的事情。 。我下面的方法是一种解决方法。
假设您有以下对象作为起点:
public class Icon {
private String name;
private String title;
// getters and setters...
}
假设您有 List
此类对象的数量,称为 icons
...
此列表会以通常的方式传递到您的 Thymeleaf 渲染器。我不使用 Spring,所以你如何做到这一点(我假设)是通过注释。我可能是错的——但是,它不应该影响下面的方法。在我的 no-Spring 方法中,列表被添加到 Thymeleaf 模型中: map.put("icons", icons);
我的父 Thymeleaf 模板中有以下内容:
<div th:replace = "/iconsfragment.html :: icons(iconlist='icons')">
</div>
我在iconsfragment.html
中有以下内容:
<div th:fragment="icons(iconlist)">
<th:block th:each="icon : ${__${iconlist}__}">
<div th:class="'icon-' + ${icon.name}" th:text="${icon.title}"></div>
</th:block>
</div>
它使用预处理器__${...}__
将参数(字符串)转换回可迭代对象。
您关心的结果 HTML 是:
<div class="icon-firstName">firstTitle</div>
<div class="icon-secondName">secondTitle</div>
当然,只有当您想以各种不同的方式重用该片段时,这才真正有意义。否则只需传递 ${icons}
对象直接指向片段。
还有我的<div>
示例当然需要适应您的 <button>
示例。
关于java - 如何将HashMap数组传递给partial,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60394042/