2014-10-01 743 views
2

列表包含2個元素[0],[1]。Thymeleaf嵌套列表/ ArrayList - 獲取所有元素的總大小

元素列表 - [0]具有嵌套的ArrayList五行 [0] [1],[2],[3],[4],[5]

[1]有4種元素 [0],[1],[2],[3],[4]

我怎樣才能獲得總長度/大小在Thymeleaf,即9?如果可能的話,我需要在任何循環之外使用它來保存一個臨時值。

這使我想到下一個問題,我如何在Thymeleaf中使用.size而不是遍歷數據結構來保存本地自定義變量?我準備好寫一個循環來獲取這個.size,如果需要的話,但我想將它存儲在一個局部變量中,我可能稍後在另一個循環中重用它!

實施例:

<div th:each="test : ${testList}"> 
    <div th:each="testItem : ${test.subArrayList}">         
      <div th:each="testItemSub : ${testItem}"> 
        <span> Get total size of "${testItemSub.name}" and store in a variable</span> 
      </div> 
    </div> 
</div> 
+2

隨着Thymeleaf有更新版本,您可以只使用$ {#lists.size(名單)}爲大小 – 2016-03-08 16:49:52

回答

2

您可以通過每http://www.thymeleaf.org/doc/usingthymeleaf.html#local-variablesth:with屬性設置的局部變量。但是,一旦設置了元素,我發現無法更新該元素中的局部變量。換句話說,與JSP不同,變量不能在視圖/模板中創建和操作。

解決您的具體使用情況是最簡單的方法:

  1. 組包含將在ArrayList作爲它的參數和返回的計數的方法的模型對象。顯然,你可以在Java代碼中實現你需要的任何邏輯。
    • 同樣,可以使用Spring bean而不是模型對象。使用語法:${@myBean.doSomething()}
  2. 使用Thymeleaf附帶的#ids表達式實用程序對象。如果您使用的編號爲'',它可以用作模板中的計數器。但是,只有在整個模板中只有一個這樣的計數器時才能使用。參考:在原有基礎上問題#idshttp://www.thymeleaf.org/doc/usingthymeleaf.html#ids

用法示例:

<div th:each="test : ${testList}"> 
    <div th:each="testItem : ${test.subArrayList}">         
      <div th:each="testItemSub : ${testItem}"> 
        <span> Get total size of "${testItemSub.name}" and store in a variable</span> 
        <!--/*/ <th:block th:text="${#ids.seq('')}"></th:block> /*/--> 
      </div> 
    </div> 
</div> 
<p>There are a total of <span th:text="${#ids.prev('')}">123</span> elements.</p> 
+0

謝謝你的答案。我使用的方法1. – 2014-10-08 21:25:49

+0

如果你想在頁面上有多個整數計數器,你可以這樣做: '$ {#strings.replace(#ids.seq('imageThumbs'),'imageThumbs','')}' – Nikki 2017-07-19 03:23:11