【问题标题】:Thymeleaf: populating checkboxes from an ArrayThymeleaf:从数组中填充复选框
【发布时间】:2019-01-07 10:21:01
【问题描述】:

我有一个使用 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>

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

【问题讨论】:

  • 您能否发布应用程序输出的内容,或 thymeleaf 中与之相关的任何错误?

标签: spring-mvc enums thymeleaf


【解决方案1】:

如果可以的话,您可能想尝试使用th:checked 而不是 th:attr,所以:

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

This 的帖子在调查时也可能会有所帮助。如果你不能使用 th:checked,切换到下面的语句应该也可以。

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

由于在比较时区分大小写,您在检查此数据时可能会遇到一些问题,在这种情况下,this 的帖子可能会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    相关资源
    最近更新 更多