如何在百里香的条件下分别渲染模板

时间:2017-09-19 08:32:28

标签: java html5 spring-mvc spring-boot thymeleaf

在我的项目中,我有多个模板,但我想在一个html页面中对其进行编码,并通过给出一些条件来渲染它。每个模板都在div标签中。但我无法通过提供一个条件来渲染一个模板,而通过提供第二个条件来渲染第二个模板。

 hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
<title>State 1</title>
</head>

<div th:fragment="contentA">
<body>

<form method="post">

    <label><b>Name</b></label>
    <input type="text" placeholder="Enter Name" name="name" v-
 model="value1"/>

    <br/>
    <br/>
    <br/>


    <label><b>Date of Birth</b></label>
    <input type="text" placeholder="Enter Birth date" name="dob" v-
    model="value2"/>

    <br/>
    <br/>
    <br/>

    <label><b>Email</b></label>
    <input type="text" placeholder="Enter Email" name="email" v-
    model="value3"/>
    <br/>
    <br/>
    <br/>
    <input type="checkbox" checked="checked" v-model="value4"/> 
    Remember me
    <p>By creating an account you agree to our <a href="#">Terms and 
   Privacy</a>.</p>

    <div class="clearfix">
        <button type="button"  class="cancelbtn">Cancel</button>
        <button type="submit" class="submitbtn">Submit</button>
    </div>
  </form>
  </body>
  </div>

<div th:fragment="contentB"> // another template
<body>
<h1 th:text="${messages}"></h1>
</body>
 </div>
</html>

这是我通过给出条件进行渲染的另一个html页面:

 helloform.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello, Ola CVS!!! </title>
</head>
<body>

<div th:if="${messages.checkstatus == 0}"
 th:replace="hello :: contentA"/>


<div th:if="${messages.checkstatus == 1}"
 th:replace="hello :: contentB" />

</body>
</html>

请通过在Model model中添加值来查找我的java代码:

   protected Response getUI(SMEvent event,Model model) {

  if(checkstate==1 && checkstatus==0)
    {

        model.addAttribute("messages.checkstatus" , 0);
        System.out.println("Entering to get the page for state 1 and 
        status 0"+ model);
        return Response.ok().entity("helloform").build();
    }

    if(checkstate==1 && checkstatus==1)
    {
        if(checkstate==1)
        {

           model.addAttribute("messages.checkstatus" , 1);

            System.out.println("Entering to get the page of state 1 and 
          status 1" + model);
            return Response.ok().entity("helloform").build();
        }

      }
   }

1 个答案:

答案 0 :(得分:1)

th:替换发生在th:之前,根据thymeleaf attribute precedence。你只需要移动th:if到替换之上的标签。像这样:

<th:block th:if="${messages.checkstatus == 0}">
  <div th:replace="hello :: contentA" />
</th:block>

<th:block th:if="${messages.checkstatus == 1}">
  <div th:replace="hello :: contentB" />
</th:block>