首页 > 解决方案 > Thymeleaf:从数组中填充复选框

问题描述

我有一个使用 Thymeleaf 进行模板的 Spring MVC 应用程序。我正在使用枚举动态生成复选框。因此,如果我的枚举文件有 3 个值,它将生成 3 个复选框:

我的枚举文件:

public enum Foods {

    PIZZA("Pizza"),
    PASTA("Pasta"),
    MAC_CHEESE("Mac and Cheese"),
    ICE_CREAM("Ice Cream"),
    BURGER("Burger"),

    private String type;

    Foods(String type) {
        this.type = type;
    }

    public String getType() {
        return this.type;
    }

}

这是我的复选框生成:

<label for="decision">What is your favorite food?</label>
<div id="decision" class="row" style="margin-top:1%;">
    <div class="col-md-4" th:each="option : ${T(in.app.model.enums.Foods).values()}">
        <div class="checkbox checkbox-custom checkbox-circle">
            <input name="decision" type="checkbox" th:id="${option.toString()}" th:value="${option}" />
            <label th:for="${option.toString()}" th:text="${option.type}"></label>
        </div>
    </div>
</div>

此代码将为每种食物类型生成 5 个复选框。一切工作到这里。我面临的问题是如何在读取保存的记录时设置选中的属性。

我通过模型视图控制器取回一个对象。该对象有一个食物属性,其值为所选食物类型的数组。

user = {
   .
   .
   food : ["PIZZA", "BURGER", "PASTA"],
   .
   .
}

现在我想遍历这个数组,如果值匹配然后设置复选框。

我正在尝试做这样的事情:

<label for="decision">What is your favorite food?</label>
<div id="decision" class="row" style="margin-top:1%;">
    <div class="col-md-4" th:each="option : ${T(in.app.model.enums.Foods).values()}">
        <div class="checkbox checkbox-custom checkbox-circle">
            <input 
                name="decision" 
                type="checkbox" 
                th:id="${option.toString()}" 
                th:value="${option}" 
                th:each="food : ${user.food}"
                th:attr="checked = ${food} == ${option} ? 'checked'"
            />
            <label th:for="${option.toString()}" th:text="${option.type}"></label>
        </div>
    </div>
</div>

我知道它是错误的(因为它不起作用),但我无法弄清楚如何遍历两个数组以显示复选框并检查它们。

标签: spring-mvcenumsthymeleaf

解决方案


You might want to try using th:checked instead of th:attr if you can, so:

th:checked="${food == option.type}"

This post might also be helpful when looking into that. If you can't use th:checked, switching to the below statement should also work.

th:attr="checked=${food == option.type} ? 'checked'" 

It also seems like you may run into some issues with checking this data due to case sensitivity while comparing, in which case this post might be helpful.


推荐阅读