如何在Thymeleaf中使用th:each从'a'到'z'循环?
实现Thymeleaf从'a'到'z'的循环
当然可以不用后端传字符数组,Thymeleaf虽然没有直接生成字母序列的内置方法,但可以借助#numbers.sequence结合ASCII码转换来实现前端直接循环。
方法1:利用ASCII码转换直接生成
小写字母'a'对应的ASCII码是97,'z'是122,先用#numbers.sequence生成这个范围内的数字序列,再把每个数字强制转换为字符即可:
<!-- 循环输出a到z的每个字母 --> <div th:each="asciiCode : ${#numbers.sequence(97, 122)}"> <span th:text="${(char)asciiCode}"></span> </div>
如果需要大写字母,只要把范围改成65('A')到90('Z')就行。
方法2:自定义Thymeleaf工具类(复用场景)
如果你的项目里需要多次用到字母序列,可以自定义一个Thymeleaf的工具方法,比如创建一个类并注册为Spring Bean,然后在模板里调用:
import org.springframework.stereotype.Component; @Component("letterUtils") public class LetterSequenceUtil { public char[] getLowercaseLetters() { char[] letters = new char[26]; for (int i = 0; i < 26; i++) { letters[i] = (char) ('a' + i); } return letters; } }
然后在模板里调用:
<div th:each="letter : ${@letterUtils.getLowercaseLetters()}"> <span th:text="${letter}"></span> </div>
不过这种方式适合频繁复用的场景,简单需求用第一种方法更高效。
相比你现在后端传数组的方式,第一种纯前端生成的方式更轻量化,不需要后端额外准备数据。
内容的提问来源于stack exchange,提问作者Francesco Dassisis
相关产品推荐
相关产品推荐

