我正在遍历我的产品列表并设置像这样的变量
List<InvoiceEntry> products = invoice.getProducts();
for (InvoiceEntry product : products) {
BigDecimal netValue = product.getProduct().getNetValue()
.setScale(2, RoundingMode.HALF_UP);
double vatRate = product.getProduct().getVatRate().getVatPercent();
BigDecimal vatValue = netValue.multiply(BigDecimal.valueOf(vatRate))
.setScale(2, RoundingMode.HALF_UP);
long amount = product.getAmount();
context.setVariable("productName",product.getProduct().getName());
context.setVariable("amount", product.getAmount());
context.setVariable("retailPrice", netValue + "zł");
context.setVariable("productNetValue",
netValue.multiply(BigDecimal.valueOf(amount)) + "zł");
context.setVariable("productVatRate", (int) (vatRate * 100) + "%");
context.setVariable("productVatValue",
vatValue.multiply(BigDecimal.valueOf(amount)) + "zł");
context.setVariable("total",
netValue.add(vatValue).multiply(BigDecimal.valueOf(amount)) + "zł");
}
String body = templateEngine.process("template", context);
emailSender.sendEmail("someEmail@gmail.com", "some title", body);
return "index";
模板代码段
<table width="100%" cellpadding="0" cellspacing="0">
<tr bgcolor="D0D0D0">
<td height="50" align="center"><h2 th:text="Name"></h2></td>
<td height="50" align="center"><h2 th:text="Amount"></h2></td>
<td height="50" align="center"><h2 th:text="RetailPrice"></h2></td>
<td height="50" align="center"><h2 th:text="NetValue"></h2></td>
<td height="50" align="center"><h2 th:text="VatRate"></h2></td>
<td height="50" align="center"><h2 th:text="VatValue"></h2></td>
<td height="50" align="center"><h2 th:text="Total"></h2></td>
</tr>
<tr bgcolor="ffffff">
<td height="50" align="center"><h2 th:text="${productName}"></h2></td>
<td height="50" align="center"><h2 th:text="${amount}"></h2></td>
<td height="50" align="center"><h2 th:text="${retailPrice}"></h2></td>
<td height="50" align="center"><h2 th:text="${productNetValue}"></h2></td>
<td height="50" align="center"><h2 th:text="${productVatRate}"></h2></td>
<td height="50" align="center"><h2 th:text="${productVatValue}"></h2></td>
<td height="50" align="center"><h2 th:text="${total}"></h2></td>
</tr>
</table>
问题是如何在不丢失先前数据的情况下创建新行的新元素? 例如,我想实现这样的目标
到目前为止,由于覆盖,我仍然只获得列表中的最后一个元素。 我是Thymeleaf的新人,非常感谢每一个帮助和小费;)
答案 0 :(得分:1)
您可以将产品列表放在模型上,而不是放置每个单独的属性。然后使用th:each
循环遍历它。
控制器
context.setVariable("products", products);
模板
<tr bgcolor="ffffff" th:each="product: ${products}">
<td height="50" align="center"><h2 th:text="${product.product.name}"></h2></td>
<td height="50" align="center"><h2 th:text="${product.amount}"></h2></td>
.
.
.
</tr>