英文:
Add attributes from list in thymeleaf
问题
我有一个在Java中的List<Tags>
,我想将每个Tag
添加到模板中的单个div中。
Tag类看起来像这样(有点像):
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个Tags。
我不知道哪些标签会出现。
如何解决这个问题?我的第一个想法是使用th:each="tag: ${list}"
,但是标签(属性)会出现在不同的div上...
我的第二个想法是使用th:attr="${list.get(0).getKey()}=${list.get(0).getValue()}"
,但是这样我需要硬编码列表可能包含的标签数量,而这是动态的...
英文:
I have a List<Tags>
in java and would like to add each Tag
to a single div in the template.
The Tag class looks like this(kinda):
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; }
}
The result I want: <div tag1Key="tag1Value" tag2Key="tag2Value"></div>
except the list can contain X amount of Tags.
I do not have info on what tags can appear.
How would one solve this problem? My first thought was a th:each="tag: ${list}"
but then the tags(attrubutes) would appear on different divs...
My second idea was the th:attr="${list.get(0).getKey()}=${list.get(0).getValue()}"
but then I would need to hard code the amount of tags the list can contain which is dynamic....
答案1
得分: 1
你可以将 th:attr
与 预处理 结合使用。
在你的控制器中,从属性生成一个字符串:
model.addAttribute("attributes", "attr1=something,attr2='bla bla'");
在模板中,使用预处理(双下划线)进行赋值,这基本上意味着它将首先替换变量,然后评估 th:attr
表达式:
<div th:attr="__${attributes}__">
英文:
You can combine th:attr
with preprocessing.
In your controller generate a string from the attributes:
model.addAttribute("attributes", "attr1=something,attr2='bla bla'");
In the template assign it with preprocessing (two underscores) which basically means that it will first replace the variable and then evaluate the th:attr
expression
<div th:attr="__${attributes}__">
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论