Thymeleaf Tutorial: Chapter 7. Conditional Execution

  • Tutorial
Table of contents

7 Conditional execution

7.1 Simple conditions: “if” (if) and “unless” (if not)

Sometimes you need a template fragment to appear only as a result of a certain condition.

For example, imagine that we want to show in the product table a column with the number of comments that exist for each product, and if there are any comments, a link to the comment page.

To do this, use attribute th: the if :

Onions2.41yes2 comment/s view

There are so many things here, so let's focus on the important line:


This code will create a link to the comments page (with URL / product / comments) with the prodId parameter set to the product identifier, but only if the product has any comments.

Let's look at the resulting markup:

Fresh Sweet Basil4.99yes0 comment/s
Italian Tomato1.25no2 comment/s view
Yellow Bell Pepper2.50yes0 comment/s
Old Cheddar18.75yes1 comment/s view

Excellent! This is exactly what we wanted.

Note that the th: if attribute will not only evaluate logical conditions. Its capabilities are slightly higher than this, and it will evaluate the specified expression as true, following these rules:

If the value is not null :
  • If the value is boolean and true
  • If the value is a number and nonzero
  • If the value is a character and non-zero
  • If the value is String and is not false, off or no
  • If the value is not a boolean, number, character or String

If the value is null , th: if will be set to false .

In addition, th: if has an inverse attribute, th: unless, which we could use in the previous example instead of using not (negation) inside the OGNL expression:


7.2 Switch statements

There is also a way to conditionally display content using the equivalent switch structure in Java: the th: switch / th: case attribute set .

User is an administrator

User is a manager

Note that as soon as one th: case attribute evaluates to true, every other th: case attribute evaluates to false in the same switch context.

The default parameter is specified as: th: case = "*" :

User is an administrator

User is a manager

User is some other thing

Also popular now: