2016-08-03 47 views
0

我有以下thymeleaf代碼。 transactionList和爲accountList是我的模型屬性在thymeleaf循環中設置屬性,基於第二個列表

<tr th:each="transaction : ${transactionList}" th:class="'account_' + ${transaction.accountId}"> 
    <td th:text="${transaction.transactionId}">0</td> 
    <td> 
     <select th:id="'account-' + ${transaction.transactionId}"> 
      <option th:each="account : ${accountList}" 
        th:value="${account.accountId}" 
        th:text="${account.name}" 
        th:selected="${transaction.accountId} == ${account.accountId}"/> 
     </select> 
    </td> 
</tr> 

我的問題是設置tr標籤的類名。 其當前設置爲

th:class="'account_' + ${transaction.accountId}" 

但我想改變它,以便它是字符串「account_」,然後爲accountList的索引,其中,transaction.accountId == account.accountId。

所以基本上我想找到accountList中accountId的哪個元素等於transaction.accountId。

所以我會不知怎麼必須循環通過accountList每一次之前th:在tr類。

我當然可以將這個添加到transactionList中包含的對象中,並且可以完成它,但是它打破了抽象,我更願意在前端執行此操作。

有什麼建議嗎?

回答

0

我找不到這樣的一個圓滑的方式,所以我創建了一個映射accountIds到索引一個新的模型屬性:

Map<String, Integer> accountIndexMap = new HashMap<>(); 
    IntStream.range(0, accountList.size()) 
      .forEach(i -> accountIndexMap.put(Long.toString(accountList.get(i).getAccountId()), i)); 

model.addAttribute("accountIndexMap", accountIndexMap); 

然後在我的thymeleaf頁我換了個:類是:

<tr th:each="transaction : ${transactionList}" th:class="'account_' + ${accountIndexMap.get('__${transaction.accountId}__')}"> 
相關問題