从 thymeleaf 列表中添加属性

Add attributes from list in thymeleaf

我在 java 中有一个 List<Tags>,我想将每个 Tag 添加到模板中的单个 div。 标签 class 看起来像这样(有点):

public class Tag {
    private String key;
    private String value;
    public Tag(String key, String value) { this.key = key; this.value = value; }
    public String getKey() { return key; }
    public String getValue() { return value; }
}

我想要的结果:<div tag1Key="tag1Value" tag2Key="tag2Value"></div> 除了列表可以包含 X 数量的标签。 我不知道可以显示哪些标签。

如何解决这个问题?我的第一个想法是 th:each="tag: ${list}" 但标签(属性)会出现在不同的 div 上...

我的第二个想法是 th:attr="${list.get(0).getKey()}=${list.get(0).getValue()}" 但是我需要硬编码列表可以包含的动态标签数量....

您可以将 th:attrpreprocessing 结合使用。

在您的控制器中从属性生成一个字符串:

model.addAttribute("attributes", "attr1=something,attr2='bla bla'");

在模板中为它分配预处理(两个下划线),这基本上意味着它将首先替换变量然后计算 th:attr 表达式

<div th:attr="__${attributes}__">