spring-boot - Thymeleaf 模板未在条件内呈现参数值
问题描述
我正在为我的 Spring Boot 应用程序使用 thymeleaf 模板。在主页下方,
<div th:replace="content :: content"></div>
和内部内容片段,
<div th:fragment="content">
<h4 th:if="${param.val== 'abc'}">SOME-TEXT</h4> // not working
<h4 th:if="${param.val== 'abc'}" th:text="${param.val}"></h4> // not working
<h4 th:text="${param.val}"></h4> // working and value is abc
<h4 th:unless="${param.val== 'abc'}" th:text="${param.val}"></h4> // working - value in html text is abc
<h4 th:unless="${param.val== 'abc'}">SOME-TEXT</h4> // Working, value is SOME-TEXT
</div>
URL: domain/?val=abc
我想显示:如果 param.val == 'abc',则在 html中显示一些文本。值“abc”进入 th:text。但是在里面:如果失败了。
似乎向 param.val 添加了一些隐藏的额外字符串?有什么建议吗?
解决方案
Thymeleaf 函数${param.val}
将返回一个名为 的请求参数val
。但这可能是一个多值对象(例如一个数组)——例如考虑这个(这是一个有效的结构):
?val=abc&val=def
因此,要使用单值字符串,您可以这样做:
<h4 th:if="${#strings.toString(param.val)} == 'abc'" th:text="'SOME-TEXT-2'">SOME-TEXT-1</h4>
这打印SOME-TEXT-2
在网页中。
或者你可以使用这个:
<h4 th:if="${#strings.toString(param.val)} == 'abc'">SOME-TEXT-1</h4>
哪个打印SOME-TEXT-1
。
只是出于兴趣,如果您使用了第一个示例val=abc&val=def
,那么您可以看到会发生什么:
<h4 th:text="${param.val}"></h4>
它打印一个数组:
[abc, def]
在处理一系列相关的复选框时,您可能会看到类似的内容(仅作为一个示例)。
更新:
对于空检查,使用 Thymeleaf,您可以这样做:
<h4 th:if="${param.val} != null and
${#strings.toString(param.val)} == 'abc'">SOME-TEXT-2</h4>
在这种特定情况下,它并不是真正需要的,因为您没有对可能导致问题的空值做任何事情。
如果您在对象中链接值,则更相关foo.bar.baz
- 您需要检查是否foo
为bar
null 以避免空指针异常。
请记住,Spring 的表达式语言具有安全导航运算符,这在这种情况下非常有用:foo.?bar.?baz
,允许您编写比单独使用 Thymeleaf 更简洁的 null 处理。但同样,与问题中的具体示例无关。