Html 使用 thymeleaf 进行索引迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20944800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:21:08  来源:igfitidea点击:

Iterate with index using thymeleaf

htmlspringjspthymeleaf

提问by Deepak Ramakrishnan Kalidass

I am new to thymeleaf and am converting all my jsp code to thymeleaf.I don't know how to convert this below code to thymeleaf.Do anyone know how to convert the below code to thymeleaf?

我是 thymeleaf 的新手,正在将我所有的 jsp 代码转换为 thymeleaf。我不知道如何将下面的代码转换为 thymeleaf。有人知道如何将下面的代码转换为thymeleaf

<logic:iterate id="id" property="idList" name="sampleForm" indexId="i">
    <label for="id<%=i%>">
      <bean:write name="id" property="id" />
    </label>
</logic:iterate>

Please tell me how to initialize the index value in thymeleafto be used in some values??

请告诉我如何初始化索引值thymeleaf以用于某些值?

回答by Tom Verelst

<label th:each="id,status : ${idList}" th:for="|id${status.index}|" th:text="${id.id}"></label>
  • th:eachwill iterate over the idList, assign each item to idand create a labelfor each item. The status of the item can be assigned by adding an extra name, separated by a comma (statusin this example).
  • th:forwill set the forattribute of the label. The pipes (|) are used for easy string concatenation.
  • th:textwill set the inner text of the label to the ID.
  • th:each将迭代idList,将每个项目分配给idlabel为每个项目创建一个。可以通过添加一个额外的名称来分配项目的状态,用逗号分隔(status在本例中)。
  • th:for将设置for标签的属性。管道 ( |) 用于简单的字符串连接。
  • th:text将标签的内部文本设置为 ID。

回答by haschibaschi

You can also use it like this:

你也可以这样使用它:

<label th:each="id : ${idList}" th:for="${'id' + idStat.index}" th:text="{id.id}">

This starts the index from 0

这从 0 开始索引

If you want to start the index from 1 use this

如果你想从 1 开始索引使用这个

<label th:each="id : ${idList}" th:for="${'id' + idStat.count}" th:text="{id.id}">

Check out the Thymeleaf documentation

查看Thymeleaf 文档