【发布时间】:2014-03-20 16:13:18
【问题描述】:
我想在我的网页中添加一个错误标志。 如何使用 Thymeleaf 检查 Spring Model 属性是真还是假?
【问题讨论】:
我想在我的网页中添加一个错误标志。 如何使用 Thymeleaf 检查 Spring Model 属性是真还是假?
【问题讨论】:
布尔文字是true 和false。
使用th:if,您最终会得到如下代码:
<div th:if="${isError} == true">
或者如果您决定使用th:unless
<div th:unless="${isError} == false">
您还可以使用#bools 实用程序类。请参考用户指南:http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#booleans
【讨论】:
您可以使用变量表达式 (${modelattribute.property}) 访问模型属性。
而且,您可以使用th:if 进行条件检查。
看起来像这样:
控制器:
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;
}
}
希望这会有所帮助。
【讨论】: