devstory

Instructions conditionnelles If, unless, switch dans Thymeleaf

  1. th:if, th:unless
  2. th:switch, th:case

1. th:if, th:unless

Dans certaines situations, vous voulez qu'un certain extrait du Thymeleaf Template apparaisse dans le résultat si une certaine condition est évaluée comme true (vraie). Pour ce faire, vous pouvez utiliser l'attribut (attribute) th:if.
Remarque : Dans Thymeleaf, une variable ou une expression est évaluée comme false (fausse) si sa valeur est null, false, 0, "false", "off", "no". Les autres cas sont évalués comme étant true (vrais).
Syntaxe :
<someHtmlTag th:if="condition">
    <!-- Other code -->
</someHtmlTag>

<!-- OR: -->

<th:block th:if="condition">
    <!-- Other code -->
</th:block>
Un autre attribut (attribute) que vous pouvez utiliser est th:unless. C'est la négativité de th:if.
<someTag th:unless = "condition"> ... </someTag>

<!-- Same as -->

<someTag th:if = "!condition"> ... </someTag>
Example th:if
Exemple de th:if :
if-example1.html (Template)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>If/Unless</title>
<style>
.product-container {
    padding: 5px;
    border: 1px solid #ccc;
    margin-top: 10px;
    height: 80px;
}
.img-container {
    float: left;
    margin-right: 5px;
}
</style>
</head>
<body>
    <h1>th:if</h1>
    <div class="product-container" th:each="product : ${products}">
        <!--/* If the product has image, this code will be rendered. */-->
        <div class="img-container" th:if="${product.image}">
            <img th:src="@{|/${product.image}|}" height="70" />
        </div>
        <div>
            <b>Code:</b> <span th:utext="${product.code}"></span>
        </div>
        <div>
            <b>Name:</b> <span th:utext="${product.name}"></span>
        </div>
    </div>
</body>
</html>
(Java Spring)
@RequestMapping("/if-example1")
public String ifExample1(Model model) {
    Product prod1 = new Product(1L, "SS-S9", "Sam Sung Galaxy S9", "samsung-s9.png");
    Product prod2 = new Product(2L, "NK-5P", "Nokia 5.1 Plus", null);
    Product prod3 = new Product(3L, "IP-7", "iPhone 7", "iphone-7.jpg");

    List<Product> list = new ArrayList<Product>();
    list.add(prod1);
    list.add(prod2);
    list.add(prod3);
    model.addAttribute("products", list);
    return "if-example1";
}
Product.java
package org.o7planning.thymeleaf.model;

public class Product {
    private Long id;
    private String code;
    private String name;
    private String image;
    public Product() {
    }
    public Product(Long id, String code, String name, String image) {
        this.id = id;
        this.code = code;
        this.name = name;
        this.image = image;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
}
Example th:if, th:unless
Exemple de th:if et th:unless :
if-unless-example1.html (Template)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>If/Unless</title>
<style>
.product-container {
    padding: 5px;
    border: 1px solid #ccc;
    margin-top: 10px;
    height: 80px;
}
.img-container {
    float: left;
    margin-right: 5px;
}
</style>
</head>
<body>
    <h1>th:if, th:unless</h1>
    <div class="product-container" th:each="product : ${products}">
        <!--/* If the product has image, this code will be rendered. */-->
        <div class="img-container" th:if="${product.image}">
            <img th:src="@{|/${product.image}|}" height="70" />
        </div>
        <!--/* If the product has no image, display default Image. */-->
        <div class="img-container" th:unless="${product.image}">
            <img th:src="@{/no-image.png}" height="70" />
        </div>
        <div>
            <b>Code:</b> <span th:utext="${product.code}"></span>
        </div>
        <div>
            <b>Name:</b> <span th:utext="${product.name}"></span>
        </div>
    </div>
</body>
</html>
(Java Spring)
@RequestMapping("/if-unless-example1")
public String ifUnlessExample1(Model model) {
    Product prod1 = new Product(1L, "SS-S9", "Sam Sung Galaxy S9", "samsung-s9.png");
    Product prod2 = new Product(2L, "NK-5P", "Nokia 5.1 Plus", null);
    Product prod3 = new Product(3L, "IP-7", "iPhone 7", "iphone-7.jpg");
    List<Product> list = new ArrayList<Product>();
    list.add(prod1);
    list.add(prod2);
    list.add(prod3);
    model.addAttribute("products", list);
    return "if-unless-example1";
}
Voir plus sur Elvis :
<!--/* Elvis Operator */-->
<p>Age: <span th:utext="${person.age}?: '(no age specified)'">27</span>.</p>

2. th:switch, th:case

EnJava vous êtes familier avec la structure switch/case. Thymeleaf a également une structure similaire qui est th:swith/th:case.
<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="${roles.manager}">User is a manager</p>
  <p th:case="'staff'">User is a staff</p>
</div>

<!-- th:switch/th:case with default case: -->

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="${roles.manager}">User is a manager</p>
  <p th:case="'staff'">User is a staff</p>
  <p th:case="*">User is some other thing</p>
</div>
Le programme évaluera les case (cas) à tour de rôle, de haut en bas. Si un caseest jugé true (vrai), il "render" le code dans ce case. Tous les autres case seront ignorés.
th:case = "*" est le case par défaut de la structure th:swith/th:case. Si tous ces case au- dessus sont évalués comme false le code du case par défaut sera "render".
Example:
switch-example.html (Template)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>th:witch/th:case</title>
</head>
<body>
    <h1>tth:witch/th:case</h1>
    <h4 th:utext="${user.userName}"></h4>
    <div th:switch="${user.role}">
        <p th:case="'admin'">User is an administrator</p>
        <p th:case="'manager'">User is a manager</p>
        <p th:case="'staff'">User is a staff</p>
        <p th:case="*">User is some other thing</p>
    </div>
</body>
</html>
(Java Spring)
@RequestMapping("/switch-example")
public String ifTestFalse(Model model) {
    User user = new User("Administrator", "admin");
    model.addAttribute("user", user); 
    return "switch-example";
}
User.java
package org.o7planning.thymeleaf.model;

public class User {
    private String userName;
    private String role;
    public User(String userName, String role) {
        this.userName = userName;
        this.role = role;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
}