【问题标题】:Boolean condition with Thymeleaf and SpringThymeleaf 和 Spring 的布尔条件
【发布时间】:2014-03-20 16:13:18
【问题描述】:

我想在我的网页中添加一个错误标志。 如何使用 Thymeleaf 检查 Spring Model 属性是真还是假?

【问题讨论】:

    标签: spring thymeleaf


    【解决方案1】:

    布尔文字是truefalse

    使用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

    【讨论】:

      【解决方案2】:

      您可以使用变量表达式 (${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;
        }
      
      }
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-09
        • 2021-11-12
        • 1970-01-01
        • 2015-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多