Thymeleaf 的条件判断是 通过 th:if 来做的,只有为真的时候,才会显示当前元素

<p th:if="${testBoolean}" >如果testBoolean 是 true ,本句话就会显示</p>

取反可以用not, 或者用th:unless.

<p th:if="${not testBoolean}" >取反 ,所以如果testBoolean 是 true ,本句话就不会显示</p>
<p th:unless="${testBoolean}" >unless 等同于上一句,所以如果testBoolean 是 true ,本句话就不会显示</p> 

除此之外,三元表达式也比较常见

<p th:text="${testBoolean}?'当testBoolean为真的时候,显示本句话,这是用三相表达式做的':''" ></p>

 

demo:
controller:

@GetMapping("/hello5") public String t5(Model model){ String html = "<p style='color:red'>html文本</p>"; model.addAttribute("html",html); model.addAttribute("t1",true); model.addAttribute("t2",true); return "index5"; }

index5.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>index5</title>
</head>
<body>

    <p th:if="${t1}" >显示</p>
    <p th:if="${not t1}">不显示</p>
    <p th:unless="${t1}">不显示</p>
    <p th:text="${t2} ? '显示':'不显示'"></p>

    <p th:text="${html}">非转义的 html 文本</p>
    <p th:utext="${html}">转义的 html 文本</p>


</body>
</html>

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/crazy-lc/p/12259013.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!