将属性从列表添加到Thymeleaf中。

huangapple go评论79阅读模式
英文:

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(&quot;attributes&quot;, &quot;attr1=something,attr2=&#39;bla bla&#39;&quot;);

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

&lt;div th:attr=&quot;__${attributes}__&quot;&gt;

huangapple
  • 本文由 发表于 2020年9月18日 15:08:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63950858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定