Thymeleaf:運算符(邏輯語句、遍歷、內置對象)


1、邏輯語句

(1)if與unless

 <hr/>
    <p th:if="1==1">if</p>
    <p th:unless="1 ne 1">unless</p>
    <hr/>
    <p th:if="1==2">if</p>
    <p th:unless="1 eq 1">unless</p>

測試結果:

(2)switch ... case語句

書寫controller向頁面提供數據:

    @RequestMapping("/test")
    public String hello(Model model){
        model.addAttribute("msg",1);
        return "test";
    }

書寫html頁面:

   <ul th:switch="${msg}">
         <li th:case="1">星期一</li>
         <li th:case="2">星期二</li>
         <li th:case="3">星期三</li>
         <li th:case="4">星期四</li>
         <li th:case="5">星期五</li>
         <li th:case="6">星期六</li>
         <li th:case="7">星期天</li>
         <li th:case="*">輸入錯誤</li>
     </ul>

測試結果:

 提供一個不在范圍內的數據:

   @RequestMapping("/test")
    public String hello(Model model){
        model.addAttribute("msg",11);
        return "test";
    }

 

2、遍歷

數據:

@Controller
public class TestController { @RequestMapping("/test") public String hello(Model model){ model.addAttribute("users", Arrays.asList("tom","jack","zhai")); return "test"; } }

模板:

<body>
   <h3 th:each="user:${users}" th:text="${user}"></h3>
</body>

測試:

 

3、內置對象

(1)時間

獲取當前時間:

<h4>[[${#dates.createNow()}]]</h4>

測試結果:

 日期的格式化:

在controller層獲取時間數據並傳遞到頁面:

  @RequestMapping("/test")
    public String hello(Model model){
        model.addAttribute("date",new Date());
        return "test";
    }

在html頁面負責獲取數據並將日期進行格式化:

<h4>[[${#dates.format(date,'yyyy年MM月dd日')}]]</h4>

測試:

(2)數字處理

小數的的格式化:

<h4>[[${#numbers.formatDecimal(3.1415926,2,3)}]]</h4>

測試結果:

數字的格式化:

<h4>[[${#numbers.formatDecimal(99999999.75433,1,'COMMA',2,'POINT')}]]</h4>

測試結果:

 COMMA是逗號,POINT是點

 

4、字符串處理

(1)截取字符串

<h4>[[${#strings.substring('美國或有60萬人死於新冠美國新冠疫情最新消息死亡多少人',0,10)}]]</h4>

測試結果:

(2)字符串處理

<h4>[[${#strings.length(message) le 20 ? message:#strings.substring(message,0,20)+'...'}]]</h4>

測試結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM