首页 > 解决方案 > 如何在 thymeleaf numbers.sequence() 方法中使用常量类中的变量?

问题描述

我在这样的Constants类中定义了两个静态变量

public static String MIN_VALUE = 1;
public static String MAX_VALUE = 10;

我想创建一个 html 选择标签,其中包含所有数字从MIN_VALUEto开始的选项MAX_VALUE。如果我在百里香中使用硬编码数字,我可以轻松做到这一点:

<select>
  <option th:each="number: ${#numbers.sequence(1, 10)}" th:value="${number}" th:text="${number}"/>
</select>

但如果我尝试这样的事情:

<option th:each="number: ${#numbers.sequence(${Constants.MIN_VALUES}, ${Constants.MAX_VALUES})}" th:value="${number}" th:text="${number}"/>

我收到此错误:

EL1043E: Unexpected token. Expected 'rparen())' but was 'lcurly({)'

如何在百里香的方法中使用我Constant班级中的变量numbers.sequence

我发现这个问题的标题几乎相似,但我没有通过model这里的属性传递我的变量限制。我可以使用thymeleaf 标签从Constants类中访问我的变量。Constants.VAR_NAME

标签: javaspringthymeleaf

解决方案


  1. 不要嵌套${...}表达式。
  2. 按照评论中的说明使用T(com.example.Constants).MIN_VALUEcom.example.Constants(完整的包和类名在哪里。)

例子:

<select>
  <option
    th:each="number: ${#numbers.sequence(T(com.example.Constants).MIN_VALUE, T(com.example.Constants).MAX_VALUE)}"
    th:value="${number}"
    th:text="${number}" />
</select>

推荐阅读