I\'d like to add an error flag in my web page. How can I to check if a Spring Model attribute is true or false with Thymeleaf?
You can access model attributes by using variable expression (${modelattribute.property}
).
And, you can use th:if for conditional checking.
It looks like this:
Controller:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping("/foo")
public String foo(Model model) {
Foo foo = new Foo();
foo.setBar(true);
model.addAttribute("foo", foo);
return "foo";
}
}
HTML:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div th:if="${foo.bar}"><p>bar is true.</p></div>
<div th:unless="${foo.bar}"><p>bar is false.</p></div>
</body>
</html>
Foo.java
public class Foo {
private boolean bar;
public boolean isBar() {
return bar;
}
public void setBar(boolean bar) {
this.bar = bar;
}
}
Hope this helps.
The boolean literals are true
and false
.
Using the th:if
you will end up with a code like:
<div th:if="${isError} == true">
or if you decide to go with the th:unless
<div th:unless="${isError} == false">
There is also a #bools
utility class that you can use. Please refer to the user guide: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#booleans