簡體   English   中英

使用 thymeleaf 同時迭代兩個列表

[英]iterate simultaneously over two lists using thymeleaf

<div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Roles
        <span class="required">*</span>
    </label>
    <thbody>
        <td><th:block th:each="myRoles : ${MyRoles}">
            <input type="checkbox" name="roles"
                th:value="${myRoles .id}" checked />
            <label th:text="${myRoles .roleName}"></label>
        </th:block>--</td>
    </thbody>

當前它只向我顯示一個列表(當前角色),我想顯示綁定在對象 ${AllRoles} 中的所有角色,並只檢查當前分配給特定用戶的那些角色。

我正在嘗試將角色保存在我的控制器中:

Set<UserRole> myRolesSet;
myRolesSet= myusr.getRoles();

這是我正在嘗試做的事情:

<thbody >
        <td><th:block th:each="allRoles : ${allrole}">
        <input  type="checkbox" name="roles" th:value="${allRoles.id}"
        th:checked="${#sets.contains(myRolesSet,allRoles.id)}? 'checked' " />
        <label th:text="${allRoles.roleName}"></label>
        </th:block></td>
</thbody>

您應該像以下代碼示例一樣執行此操作:

首先,您需要將選定的角色放入控制器方法的 Map 中,如下所示:

HashMap<Integer, Role> myRolesMap = new HashMap<Integer, Role>();

在這種情況下,我假設您使用 Integer 鍵作為哈希映射。

其次,您必須遍歷 AllRoles 列表並確定用戶是否具有當前迭代的角色,然后您應該選中該復選框。

    <thbody>
        <td><th:block th:each="role: ${AllRoles}">
            <input type="checkbox" name="roles"
                th:value="${role.id}" th:checked="${#maps.containsKey(myRolesMap, role.id)}" />
            <label th:text="${role.roleName}"></label>
        </th:block>--</td>
    </thbody>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM