Tom*_*rma 8 java expression thymeleaf
我正在使用百里香标准方言并尝试在表单中呈现复选框列表.渲染是可以的,但问题是我尝试使用thymeleaf#lists.contains()表达式实用程序方法将"checked"属性应用于复选框.
所以我有一个包含以下字段的模型类:
private List<Template> templates;
@FormParam("selectedTemplates")
private List<String> selectedTemplates = Lists.newArrayList();
Run Code Online (Sandbox Code Playgroud)
一个Thymeleaf模板html片段:
<div th:each="template : *{templates}">
<input type="checkbox" name="selectedTemplates" th:value="${template.id}"
th:checked="${#lists.contains(product.selectedTemplates, template.id)}" />
<label th:text="${template.filename} + ' (' + ${template.description} + ')'" />
<!-- Attempt to use the list contains to check the field -->
<div th:text="${product.selectedTemplates}"/>
<div th:text="${template.id}"/>
<div th:text="${#lists.contains(product.selectedTemplates, template.id)}" />
</div>
Run Code Online (Sandbox Code Playgroud)
页面上的输出应该选择一个复选框.
<input type="checkbox" name="selectedTemplates" value="4" /> (Template Name)
<div>[4,5]</div>
<div>4</div>
<div>false<div>
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我打印了具有值[4,5]的列表,并使用#lists.contains方法查看它是否包含template.id,但是,该方法始终返回false.我甚至尝试了一些硬编码的id来测试方法,我总是得到"假"回来.
例如:
<div th:text="${product.selectedTemplates}"/>
<div th:text="${#lists.contains(product.selectedTemplates, 4)}" />
Run Code Online (Sandbox Code Playgroud)
打印[4,5]错误
<div th:text="${product.selectedTemplates}"/>
<div th:text="${#lists.contains(product.selectedTemplates, '4')}" />
Run Code Online (Sandbox Code Playgroud)
打印[4,5]错误
不知道我做错了什么,但它似乎很直接,不知道还有什么可以尝试.我的猜测是语法有问题.非常感谢任何建议或意见.我无法找到解决这个问题的任何资源,百日咳指南会快速浏览该部分.
Tom*_*rma 17
我在百里香论坛上提出了这个答案,并得到一些帮助来确定根本原因和解决方案.见[ http://forum.thymeleaf.org/Problem-with-thymeleaf-expression-utility-lists-contains-td4027317.html] [1 ]
实质上,单个字符串默认被解释为字符类型,因此永远不会匹配列表中的任何字符串.多字符字符串计算为字符串类型因此按预期工作.通过将搜索的值封装在html编码的引号中,解析器被强制将单个字符串评估为字符串类型而不是char类型.例如:
<div th:text="${#lists.contains(testList, "3")}"/>
<div th:text="${#lists.contains(testList, "P")}"/>
Run Code Online (Sandbox Code Playgroud)
只是想发布这个以防任何人对根本原因和解决方案感兴趣.
我知道这个问题很旧,但是我发布了这个答案,因此对其他遇到相同问题的用户很有用。
我不知道是您还是其他用户,但在这里我发现我们必须添加
''+ template.id
所以:
th:checked="${#lists.contains(product.selectedTemplates, '' + template.id)}"
Run Code Online (Sandbox Code Playgroud)
对我来说,它起作用了!谢谢