thymeleaf 简介和语法

1 thymeleaf 简介
2 thymeleaf 语法 - th 属性
3 thymeleaf 语法 - 内置方法
4 thymeleaf 语法 - 标准表达式


=========================================================

1 thymeleaf 简介 


  和过去学的jsp很象,是一个模板引擎
  
  1)创建 Springboot maven 项目  
       pom 中的配置如下
       <parent>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>2.2.9.RELEASE</version>
       </parent>
       
     <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
     </dependencies>
     
  2)导入thymeleaf相关的启动器
       <dependency>
         <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</artifactId>
       </dependency>
       
    3)创建模板文件
       src/main/resources/ 
       建一个叫 templates 的目录 (必须是这个名字)
       里面放模板文件  demo.html 内容:
               
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8">
        <title> </title>
        </head>
        <body>
            <div th:text="${msg}">这是div </div>
            <p th:text="${info}">这是段落   </p>
        </body>
        </html>

 4) 创建控制层 UserController
            package com.controller;
            import org.springframework.stereotype.Controller;
            import org.springframework.ui.ModelMap;
            import org.springframework.web.bind.annotation.RequestMapping;
            
            @Controller
            public class UserController {    
                @RequestMapping("/gogogo")
                public String gotoDemo(ModelMap m) {
                    m.put("msg","模板引擎测试成功");
                    m.put("info","我是打酱油的");
                    return "demo"; //==>src/main/resources/templates/demo.html    
                }
            }
            
    5) 创建启动类
        package com;
        import org.springframework.boot.SpringApplication;
        import org.springframework.boot.autoconfigure.SpringBootApplication;
        
        @SpringBootApplication
        public class App {
            public static void main(String[] args) {
                SpringApplication.run(App.class, args);
            }
        }
    
    6) 启动,访问
     http://localhost:8080/gogogo


     2 thymeleaf 语法 - th 属性


        建 配置文件 application.properties 
        放在 src/main/resources/ 
        
        spring.thymeleaf.cache=false
        关闭它的缓存
        
        一般来说,html元素有的属性,thymeleaf 都有
     ① th:text  th:utext   设置文本元素的内容
     ② th:value  设置元素的value值
     ③ th:each 循环
     ④ th:if  判断
     ⑤ th:object 声明变量,一般和 *{} 配合使用
     ⑥ th:fragment 声明片段
     ⑦ th:insert   th:replace  th:include  引入片段
     ⑧ th:attr 访问属性
        
     //控制层
        @RequestMapping("/thymeleaf")
            public String  thymeleaf(ModelMap m) {
                m.put("thText","<h1>这是thText的内容</h1>");
                m.put("thUext","<h1>这是thUext的内容,会解析标签</h1>");
                
                m.put("thValue","默认是100");
                
                m.put("myList",Arrays.asList("增加","删除","修改","退出","锁定"));
                
            //    m.put("msg","这是一个不空的字符串,你中奖子");
                m.put("msg",null);
                
                UserInfo user=new UserInfo();
                user.setId(9);
                user.setUserName("刘铁轮");
                user.setPassword("12345");
                user.setNote("超级管理员");
                m.put("user",user);
            
                return "tymeleaf-pages/thymeleaf";
            }
            
    页面:  src/main/resources/templates/tymeleaf-pages/thymeleaf.html
        <!DOCTYPE html>
        <html xmlns:th="http://www.thymeleaf.org">
        <head>
        <meta charset="UTF-8">
        <title></title>
        </head>
        <body>
            <p th:text="${thText}"></p>
            <p th:utext="${thUext}"></p>
            
            <input th:value="${thValue}" />
         
            <ul th:each="item: ${myList}">
                <li th:text="${item}"> </li>
            </ul>
            
            <ul>
                <li th:each="item: ${myList}"  th:text="${item}"> </li>
            </ul>
            
            <p th:if="${not #strings.isEmpty(msg)}" >
                这是一个段落 ,表示我中奖了
            </p>
            
            <div th:text="${user.id}"></div>
            <div th:text="${user.userName}"></div>
            <div th:text="${user.password}"></div>
            <div th:text="${user.note}"></div>
            
            <div th:object="${user}">
                <div th:text="*{id}"></div>
                <div th:text="*{userName}"></div>
                <div th:text="*{password}"></div>
                <div th:text="*{note}"></div>
            </div>
         </body>
        </html>

3 thymeleaf 语法 - 内置方法


  ① strings  处理字符串 (基本上可以认为,String类常用的处理函数它都有)
                            equals,length,trim,toUpperCase, replace,endsWith,contains
  ② numbers 数值格式化 比如 formatDecimal 
  ③ bools 常用的方法有 isTrue,isFalse
  ④ arrays 处理数组 ,toArray,length,isEmpty,contains,contiansAll
  ⑤ lists,sets 集合方法 toList, size,isEmpty,contains,sort
  ⑥ maps 处理map集合 size,containsKey,containsValue ,isEmpty
  ⑦ dates  处理日期  fomat ,year,month,day,hour,createNow 
  
      @RequestMapping("/varexpressions")
    public String  varexpressions(ModelMap m) {
       m.put("str", "this is a cat"); 
       m.put("myArray", new Integer[]{1,3,5,7,9});  //必须是Integer
       m.put("myList", Arrays.asList(9,3,4,6,1,5,2,4,6,8,10));
       
       Map<String,Object> myMap=new HashMap<String,Object>();
       myMap.put("一号","嗷嗷");
       myMap.put("二号","娃哈哈");
       m.put("myMap",myMap);  
       m.put("birthday",new Date());

       return "tymeleaf-pages/varexpressions";    
    }
  
    在 tymeleaf-pages/varexpressions.html 中:
        <!DOCTYPE html>
        <html  xmlns:th="http://www.thymeleaf.org">
        <head>
        <meta charset="UTF-8">
        <title>Insert title here</title>
        </head>
        <body>
           <div th:if="${not #strings.isEmpty(str)}">
                       传过来的字符串不空,则显示以下内容:
                  <hr />
                  <p>原始串: <span th:text="${str}"></span></p>
                  <p>变大写: <span th:text="${#strings.toUpperCase(str)}"></span></p>
                  <p>equals: <span th:text="${#strings.equals(str,'this is a dog')}"></span></p>
                  <p>indexOf: <span th:text="${#strings.indexOf(str,'a')}"></span>
                  <p>截取: <span th:text="${#strings.substring(str,2,8)}"></span>
                  <p>包含: <span th:text="${#strings.contains(str,'is')}"></span>
           </div>
           
           <div th:if="${not #arrays.isEmpty(myArray)}">
                   传过来的数组不空,则显示以下内容:
                  <hr />
                  <p>长度: <span th:text="${#arrays.length(myArray)}"></span></p>
                  <p>包含: <span th:text="${#arrays.contains(myArray,7)}"></span>
           </div>
           
           <div th:if="${not #lists.isEmpty(myList)}">
                       传过来的list集合不空,则显示以下内容:
                  <hr />
                  <p>size:  <span th:text="${ #lists.size(myList)}"></span></p>
                  <p>包含: <span  th:text="${ #lists.contains(myList,4)}"></span></p>
                  <p>排序  <span th:text="${#lists.sort(myList)}"></span></p> 
           </div>
           
           <div th:if="${not #maps.isEmpty(myMap)}">
                   <p>size: <span th:text="${#maps.size(myMap)}"></span></p>
                   <p>是否包含某个key: <span th:text="${#maps.containsKey(myMap,'一号')}"></span></p>
                   <p>是否包含某个value: <span th:text="${#maps.containsValue(myMap,'川')}"></span></p>
           </div>
           
           <div>
                 <p>原始: <span th:text="${birthday}"></span></p>  //Fri Oct 29 15:44:25 CST 2021
                 <p>format: <span  th:text="${#dates.format(birthday)}"></span></p> //2021年10月29日 下午03时44分25秒
                 <p>自定制:   <span th:text="${#dates.format(birthday,'yyyy-MM-dd HH:mm:ss')}"></span></p> //2021-10-29 15:48:17
                 <p>年:<span th:text="${#dates.year(birthday)}"></span></p>
                 <p>月:<span th:text="${#dates.month(birthday)}"></span></p>
                 <p>月的中文名:<span th:text="${#dates.monthName(birthday)}"></span></p>
                 <p>周几:<span th:text="${#dates.dayOfWeek(birthday)}"></span></p>
                 <p>周几中文名:<span th:text="${#dates.dayOfWeekName(birthday)}"></span></p>
                 <p>分钟:<span th:text="${#dates.minute(birthday)}"></span></p>
                 <p>当前时间:<span th:text="${#dates.createNow()}"></span></p>
           </div>
        
        </body>
        </html>

 4 thymeleaf 语法 - 标准表达式


        ① ${...}  变量表达式
        ② *{...}  选择表达式
        ③ #{...}  消息表达式
        ④ @{...}  链接表达式
        ⑤ ~{...}  片段表达式
        
        ① ${...}  变量表达式
           变量表达式有丰富的内置方法 
           可以用它访问对象的属性
           可以使用 ctx, vars, locale,request,response,session,servletContext 等内置对象
             说明: 
              ctx :上下文对象
              vars:上下文变量
              locale: 上下文语言环境
              request: HttpServltRequest
              response:HttpServletResponse
              session: 会话 HttpSession
              servletContext :ServletContext 对象 (相当于jsp中的 application对象)
                
                //例 
                <span th:text="${msg}"  ></span>
                <span th:text="${session.admin.userName}" ></span>
                
      ② *{...}  选择表达式
            <div th:object="${user}">
                <div th:text="*{id}"></div>
                <div th:text="*{userName}"></div>
                <div th:text="*{password}"></div>
                <div th:text="*{note}"></div>
            </div>
            
      ③ #{...}  消息表达式
         从配置文件中提取出信息,一般用于国际化场景
         <label th:text="#{userName}"> </label>
         
         配置文件一般有多份
          中文:userName:用户名
          英文:userName:this is user name
          
      ④ @{...}  链接表达式
         不管是静态资源的引入,还是表单的请求,凡是有url的地方,都可以用
         链接表达式 
         
         链接表达式结构
         @{/url}
         
         //例:
            <img src="images/b.jpg" />
         上面的写法用链接表达式:
          <img th:src="@{/images/b.jpg}" />
          
         //例 
          <form th:action="@{/gogogo}">
             ...
          </form
          
         //例
              <a href="gogogo" >去 demo.html</a> 
                  上面的写法用链接表达式:
                <a th:href="@{/gogogo}" >去 demo.html</a>
          
           //例
        <a href="UserSerlvet?flag=del&id=10" >去 demo.html</a>
            上面的写法用链接表达式:
        <a th:href="@{/UserSerlvet(falg=del,id=10)}" >去 demo.html</a>
         
              

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无处安放的小曾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值