Boolean condition with Thymeleaf and Spring

后端 未结 2 1782
暗喜
暗喜 2021-02-13 20:33

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?

相关标签:
2条回答
  • 2021-02-13 21:14

    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.

    0 讨论(0)
  • 2021-02-13 21:21

    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

    0 讨论(0)
提交回复
热议问题