2016-08-03 155 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}__')}">