简体   繁体   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>

Current it is showing me only one list(present roles), I want to show all roles which are bind in object ${AllRoles} and checked only those roles which are currently given to a particular user.当前它只向我显示一个列表(当前角色),我想显示绑定在对象 ${AllRoles} 中的所有角色,并只检查当前分配给特定用户的那些角色。

I am trying to save roles in set in my controller:我正在尝试将角色保存在我的控制器中:

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

Here's how I am trying to do in view:这是我正在尝试做的事情:

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

You should be doing this like the following code sample:您应该像以下代码示例一样执行此操作:

First you need to put selected roles in a Map in your controller method as follows:首先,您需要将选定的角色放入控制器方法的 Map 中,如下所示:

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

In this case I assume you are using an Integer key for your hash map.在这种情况下,我假设您使用 Integer 键作为哈希映射。

Secondly you have to iterate over AllRoles list and decide if the user has the currently iterated Role then you should check the checkbox.其次,您必须遍历 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