【发布时间】:2022-01-11 00:54:50
【问题描述】:
我正在尝试使用 Thymeleaf 显示数组中的每一行 - 在他们的 documentation 之后,我无法使用 th:each 中的以下任何属性:
-
当前迭代索引,从0开始。这是索引 属性。
-
当前迭代索引,从 1 开始。这是计数 属性。
userinput.html:
<tr th:each="year : ${years}">
<th scope="row" th:text="${years}"></th>
<th scope="row" th:text="${bdcInterest}"></th>
<td th:text="${bdAmount}"></td>
</tr>
CalculatorController.java:
@RequestMapping(value = "/submit", method = RequestMethod.GET)
public String userInput(Model model, BigDecimal lumpsum, BigDecimal interestrate, BigDecimal monthlywithdrawal) {
BigDecimal initialinvestment = lumpsum;
BigDecimal[] bdAmount = new BigDecimal[11];
BigDecimal[] bdcInterest = new BigDecimal[11];
BigDecimal[] initialInvestment = new BigDecimal[11];
int[] years = new int[11];
bdcInterest[0] = new BigDecimal(0);
initialInvestment[0] = initialinvestment;
int increment = 1;
while(increment < 10) {
BigDecimal amount = lumpsum
.multiply(BigDecimal
.valueOf(1)
.add(interestrate
.divide(BigDecimal
.valueOf(100)))
.subtract(monthlywithdrawal
.multiply(BigDecimal
.valueOf(12)))); // Calculate the total yearly amount
BigDecimal cInterest = amount.subtract(initialinvestment); // Calculate only the interest earned
bdAmount[increment] = amount;
bdcInterest[increment] = cInterest;
initialInvestment[increment] = initialinvestment;
years[increment] = increment;
lumpsum = amount;
increment++;
}
model.addAttribute("years", years);
model.addAttribute("initialInvestment", initialInvestment);
model.addAttribute("bdAmount", bdAmount);
model.addAttribute("bdcInterest", bdcInterest);
return "userinput";
}
【问题讨论】:
-
在您的 Thymeleaf 表达式
th:each="year,id : ${increment}"中,${increment}是什么?它应该评估为一个列表或一个数组——Thymeleaf 可以迭代的东西。在你的情况下,它似乎没有评估任何东西。您是否要迭代${year}或类似的东西?目前尚不清楚预期的结果是什么。 (如果您的 Java 变量是用于列表/数组的复数形式,也可能会更清楚一些 - 例如,years而不是year。) -
我的猜测,基于上述评论:
th:each="year : ${years}"- 假设您将 Java 变量从year更改为years。 -
@andrewJames 感谢您的回复 - 我刚刚更新了上面的代码。希望这可以澄清 - Thymeleaf 表达式
<tr th:each="year : ${years}">旨在遍历数组,每年显示相关信息。它currently displays the memory location 为每个数组,而不是里面的信息。我在这里哪里出错了?感谢您的宝贵时间 -
您仍在尝试在此处显示
${years}:<th scope="row" th:text="${years}"></th>。应该是th:text="${year}"。然后您还尝试在此处显示对象数组:th:text="${bdcInterest}"和此处:th:text="${bdAmount}",而不是访问每个数组中的特定索引。 -
考虑到你的方法(使用多个数组),你也让事情变得比他们需要的更复杂。相反,您应该考虑创建一个包含对象的 Java
List,其中每个对象包含一个年份值,以及利息、投资、金额的相关值。在这种情况下,Thymeleaf 迭代变得更加简洁和简单。
标签: thymeleaf