【问题标题】:Thymeleaf th:each adding coma between elementsThymeleaf th:each 在元素之间添加逗号
【发布时间】:2016-07-05 09:23:32
【问题描述】:

我有收藏X

我遍历它并这样写:

<span th:each="a, stat : ${X}"
      th:text="${X[__${stat.index}__].someProperty} + ','">
</span>

我的另一个尝试是:

<span th:each="a, stat : ${X}" th:for="|a${stat.index}|"
      th:text="${X[__${stat.index}__].someProperty} + ','">
</span>

不幸的是输出是一样的。

span中的输出是:

test1, test2, test3,

我希望输出是:

test1, test2, test3

末尾没有逗号。我怎样才能做到这一点?

解决方案:

  1. 注意与元素类型 span 关联的属性 th:text 的值不得包含“。

代码:

<span th:each="a, stat : ${X}"
      th:text=" ${X[__${stat.index}__].someProperty} +  (${stat.size-1 > stat.index}? ',':'') ">
</span>

【问题讨论】:

  • 我不知道百里香,但你不能添加条件并检查第一个/最后一个元素吗? (Ofc 如果您首先检查,那么如果它不是第一个,则在新元素之前添加逗号。)
  • 我不确定如何在 Thymeleaf 中做到这一点,这就是我问的原因
  • 看看这里(快速搜索的顶部结果):thymeleaf.org/doc/tutorials/2.1/…
  • 是的,我看到了,但我的情况更困难,我们需要检查它是否是最后一个索引,如果是则不要添加。有很多简单的例子。
  • 尝试适应这些例子(首先理解它们),例如像这样的东西会起作用吗? (${stat.index &gt; 0}? ',':'') + ${X[__${stat.index}__].someProperty}(如果索引大于0,则在新元素前添加逗号)。

标签: java spring thymeleaf


【解决方案1】:

Thymeleaf 有一个迭代属性 last 请参阅此处的文档:http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#keeping-iteration-status

使用

<span th:each="a, iterStat : ${X}" th:text="!${iterStat.last} ? ${a} + ',': ${a}"></span>

【讨论】:

  • 您在“!”之后省略了“$”符号。它应该是 !${iterStat.last}
  • 对于 Spring Boot,有没有更干净的方法来做到这一点?喜欢把它放在格式化程序或其他东西中?
  • @DavidTroyer 确定有多种方法可以做到这一点。但是您正在为视图操作集合。在 HTML 中执行此操作允许您在视图中操作集合。
  • 我的 intellij 想法将此语法突出显示为错误,所以我像这样更改它并且它有效: th:text="${!iterStat.last} ? ${a} + ',': ${a}"
猜你喜欢
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 2021-11-09
  • 1970-01-01
相关资源
最近更新 更多