Thymeleaf列表中的最后一个元素

时间:2019-08-14 10:57:06

标签: thymeleaf

我在Thymeleaf中有一个列表,我想在div中使用th:with来获取列表中的最后一个元素。我尝试过:

<div th:if="${not #lists.isEmpty(licence.registrations)}" 
            th:with="lastRegistation=${licence.registrations[__(#lists.size(licence.registrations) - 1)__]}">
    <tr>
        <td>Name</td>
        <td><span th:text="${lastRegistration.name}"/></td>
    </tr>
</div>

但是这给了我错误:

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "(#lists.size(licence.registrations) - 1)" (template: "admin/viewLicence.html" - line 103, col 10)

有人知道我可以用Thymeleaf获取列表中的最后一项吗?

干杯

尼尔

1 个答案:

答案 0 :(得分:1)

如果使用预处理,则需要用${...}括住表达式。像这样:

    th:with="lastRegistration=${licence.registrations[__${#lists.size(licence.registrations) - 1}__]}"

话虽如此,在这种情况下没有理由使用预处理。 (而且我也会删除多余的未使用标签。)这将起作用:

<tr th:if="${not #lists.isEmpty(licence.registrations)}"
    th:with="lastRegistration=${licence.registrations[#lists.size(licence.registrations) - 1]}">
    <td>Name</td>
    <td th:text="${lastRegistration.name}" />
</tr>

您也可以选择集合和进行投影,但是我不确定这是否合适。尽管如此,它似乎仍然有效:

<tr th:if="${not #lists.isEmpty(licence.registrations)}">
    <td>Name</td>
    <td th:text="${licence.registrations.![name].$[true]}" />
</tr>