右耳菌-邓小白的Java架构师的修炼之路

Thymeleaf的语法详情及使用

2022-05-05  本文已影响0人  右耳菌

官网: https://www.thymeleaf.org/documentation.html

1. 什么是 Thymeleaf

2. Thymeleaf的特点

  1. Thymeleaf在不管是否连接服务器的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。
  2. Thymeleaf开箱即用的特性。它支持标准方言和Spring 方言,可以直接套用模板实现JSTL、OGNL表达式效果,避免每天套模板、改JSTL、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  3. Thymeleaf提供Spring标准方言和一个与SpringMVC完美集成的可选模块,可以快速地实现表单绑定、属性编辑器、国际化等功能
  4. Thymeleaf相关知识脑图


    Thymeleaf相关知识脑图

3. Thymeleaf的快速入门 (简单例子)

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
spring.thymeleaf.cache=false
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>欢迎使用Thymeleaf模板</p>
    <p th:text="${msg}">这是静态段落文字</p>
</body>
</html>
package cn.lazyfennec.springbootthymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author: Neco
 * @Description:
 * @Date: create in 2022/5/4 16:20
 */
@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(ModelMap map) {
        map.addAttribute("msg", "Hello Neco!!!");
        return "hello";
    }

}

4. Thymeleaf 的基本语法 - th属性

  • 文本拼接:||
  • 文本信息:th:text,th:id,th:value...
  • 文本信息(可以解析HTML各位): th:utext
    @RequestMapping("/hello")
    public String hello(ModelMap map){
        map.addAttribute("message","你好<b>这里加粗了</b>");
        map.put("id","这是id");
        map.put("value","这是value");
        map.put("utext","这是utext里面的内容<b>这里加粗了</b>");
        return "hello";
    }
<body>
    <!--文本属性-字符串的拼接:写法1-->
    <p th:text="|welcome to shanghai,${message}|"></p>
    <!--文本属性-字符串的拼接:写法2-->
    <p th:utext="'welcome to shanghai,'+${message}"></p>
    <!--文本属性-id属性-->
    <p th:id="${id}"></p>
    <!--文本属性-value属性-->
    <input th:value="${value}"/>
    <!--使用内联标签来书写-->
    <!--不带html的解析,类似于th:text-->
    <p>[[|welcome to shanghai,${message}|]]</p>
    <!--带html的解析,类似于th:utext-->
    <p>[('welcome to shanghai,'+${message})]</p>
    <!--也可以直接写文本-->
    <p>[['welcome to shanghai']]</p>
</body>
  • if判断:th:if
  • unless判断:th:unless
  • switch判断:th:switch...th:case
    @RequestMapping("/if")
    public String hello(ModelMap map){
        map.put("flag","yes");
        map.put("baidu","http://www.baidu.com");
        map.put("taobao","http://www.taobao.com");
        map.put("age",19);
        return "if";
    }
<body>
    <!--if:如果条件成立,就展示-->
    <!--th:href:允许在href属性里面使用thymeleaf语法,超链接需要用@{}开头,里面可以写model里面的key-->
    <a th:if="${flag eq 'yes'}" th:href="@{${baidu}}">baidu1</a><br>
    <!--th:href:专门用来使用URL地址的,既可以直接像上面那样在里面直接写${},
    也可以先定义个变量用大括号括起来然后在url的最后面使用一个小括号来对该变量进行赋值-->
    <a th:if="${flag eq 'yes'}"
       th:href="@{{baidusite}(baidusite=${baidu})}">baidu2</a><br>
    <!--直接在href里面写${}是无法获取到后台model里面的数据的-->
    <a th:if="${flag eq 'yes'}" href="${baidu}">baidu3</a><br>
    <!--不使用th:href的话,href里面只能写死的数据-->
    <a th:if="${flag eq 'no'}" href="http://www.baidu.com">baidu4</a><br>
    <!--unless:如果条件不成立,就展示-->
    <a th:unless="${flag eq 'no'}" th:href="@{http://www.taobao.com}">taobao</a>
    <!--使用switch-->
    <div th:switch="${age}">
        <p th:case="18">这是张三</p>
        <p th:case="19">这是李四</p>
        <p th:case="20">这是王五</p>
        <p th:case="*">这是谁我不认识</p>
    </div>
</body>
  • th:each迭代list
  • th:each的内置属性
  • th:each迭代map
    @RequestMapping("/list")
    public String list(ModelMap map){
        List<User> list = getUserList();
        map.addAttribute("list",list);
        return "list";
    }
  <table>
       <tr>
           <th>姓名</th>
           <th>年龄</th>
           <th>密码</th>
       </tr>
       <tr th:each="user:${list}">
           <td th:text="${user.name}"></td>
           <td th:text="${user.age}"></td>
           <td th:text="${user.pass}"></td>
       </tr>
   </table>

5. Thymeleaf的表达式语法

  • a) 可以获取对象的属性和方法
  • b) 可以使用ctx, vars, locale, request, response, session, servletContext内置对象
  • c) 可以使用dates, numbers, strings, objects, arrays, lists, sets, maps等内置方法
  • a) 无参:@{/xxx}
  • b) 有参:@{/xxx(k1=v1,k2=v2)},对应url结构:xxx?k1=v1&k2=v2
  • c) 引入本地资源:@{/项目本地的资源路径}
  • d) 引入外部资源:@{/webjars/资源在jar包中的路径}
  • 语法和变量表达式相比多了个获取参数的方式
  • 消息源主要是properties文件
  • 语法:~[templatename:fragmentname}或者~[templatename:.id},如果省略templatename,它将在当前页面进行寻找指定的代码块,注意:~可以省略
    a) templatename:模版名,定义模板的写法:<footer th:fragment="copy">
    b) fragmentname:片段名,引入模板的写法: <div th:insert="comm/foot : copy">
    c) id: HTML的id选择器,使用时要在前面加上#号,不支持class选择器
  • 代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。
    a) th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中
    b) th:replace:将代码块片段整个替换使用了th:replace的HTML标签中
    c) th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中
  • 两者获取对象里边属性的方法
  • 两者进行混用的条件

6. Thymeleaf中表达式支持的语法

  • 文本文字: 'one text','Another one!',...
  • 数字文字:0,34,3.0,12.3,...
  • 布尔文字: true,false
  • 空字面: null
  • 字符串连接:+
  • 文字替代:|The name is ${name}
  • 运算符: +,-,*,/,%
  • 二元运算符:and,or
  • 布尔否定(一元运算符)∶ !, not
  • 比较:>, <,>=,<= (gt,lt,ge,le)
  • 相等判断:==,!= (eq,ne)
  • lF-THEN:(if) ? (then)
  • lF-THEN-ELSE: (if) ? (then) : (else)
  • 默认: (value) ?: (defaultvalue)

7. Thymeleaf中的基础对象

注意:以上三个不带#的对象,都拥有以下方法:size(),isEmpty(),containsKey(), .key

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>if,unless</title>
</head>
<body>
    <h1>ctx上下文对象</h1>
    <p th:text="${#ctx}"></p>
    <h1>ctx获取保存在map里的数据</h1>
    <p th:text="${#ctx.getVariable('a')}"></p>
    <h1>vars上下文变量</h1>
    <p th:text="${#ctx}"></p>
    <h1>locale区域对象</h1>
    <p th:text="${#locale}"></p>
    <p th:text="${#locale.country}"></p>
    <h1>param的使用</h1>
<!--    http://127.0.0.1:8088/baseObject?a=1&b=2&c=3,
    param代表获取到请求里的参数-->
    <p th:text="|size:${param.size()},a:${param.a}|"></p>
    <h1>来获取session里面的对象</h1>
    <p th:text="${#session.getAttribute('session')}"></p>
    <p th:text="${session.session}"></p>
</body>
</html>
package com.study.thymeleaf.thymeleafdemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author 来苏
 * 测试基础对象
 * #ctx、#vars、#locale
 */
@Controller
public class BaseObjectController {
    @RequestMapping("/baseObject")
    public String map1(ModelMap map, HttpServletRequest request, HttpSession session) {
        map.put("a", 123);
        map.put("b", "bbb");
        request.setAttribute("request", "123");
        session.setAttribute("session", "321");
        return "base";
    }
}

8. Thymeleaf的常用工具类

9. body内的内联

<!--内联标签的使用-->
    <!--内联写法1-->
    <p >[[|welcome to china,${text}|]]</p>
    <!--内联写法2-->
    <p>[('welcome to china,'+${text})]</p>
    <!--内联写法3-->
    <p>[('welcome to china')]</p>
<body th:inline="none">

10. JS里的内联

<script th:inline="javascript">
        var name = [[${name}]];
        var userName = [[${user.name}]];
        var userAge = [[${user.age}]];
        var userPass = [[${user.pass}]];
        alert("name:"+name+",userName:"+userName+",userAge:"
            +userAge+",userPass:"+userPass);
</script>

11. css里的内联

    <style type="text/css" th:inline="css" th:with="color='yellow',
        fontSize='25px'">
        p{
            /*这里是一个注释*/
            color: /*[[${color}]]*/ red;
            /*fontSize需要使用[()]来忽略HTML的转义*/
            font-size:[(${fontSize})];
        }
    </style>

如果觉得有收获就点个赞吧,更多知识,请点击关注查看我的主页信息哦~

上一篇 下一篇

猜你喜欢

热点阅读