Thymeleaf 和 Spring 的布尔条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22538900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Boolean condition with Thymeleaf and Spring
提问by vdenotaris
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?
我想在我的网页中添加一个错误标志。如何使用 Thymeleaf 检查 Spring 模型属性是真还是假?
回答by Garis M Suero
The boolean literals are true
and false
.
布尔文字是true
和false
。
Using the th:if
you will end up with a code like:
使用th:if
你最终会得到如下代码:
<div th:if="${isError} == true">
or if you decide to go with the th:unless
或者如果你决定去 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
#bools
您还可以使用一个实用程序类。请参考用户指南:http: //www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#booleans
回答by Shinichi Kai
You can access model attributes by using variable expression (${modelattribute.property}
).
您可以使用变量表达式 ( ${modelattribute.property}
)访问模型属性。
And, you can use th:iffor conditional checking.
而且,您可以使用th:if进行条件检查。
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:
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.
希望这可以帮助。