根据第二个列表

时间:2016-08-03 19:28:05

标签: spring-boot thymeleaf

我有以下百里香码。 transactionList和accountList是我的模型属性

<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。

因此,每次在tr。

中的th:class之前,我都会以某种方式遍历accountList

我当然可以将它添加到transactionList中包含的对象中并使用它完成,但它会破坏抽象,我宁愿在前端执行此操作。

有什么建议吗?

1 个答案:

答案 0 :(得分: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);

然后在我的百万富翁页面中,我将第一课改为:

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