Thymemeaf

Thymemeaf

提示:基于SpringBoot的笔记

简介

是一个现代化的,服务端的java模板引擎

优点:语法简单,贴近jsp

缺点:不是一个高性能的模板引擎,只适合单体应用

Thymemeaf的基础使用

基本语法

表达式名字 语法 用途
变量取值 ${...} 获取请求域对象,session域、对象等值
选择变量 *{...} 获取上下文对象值
消息 #{...} 获取国际化等 值
链接 @{...} 生成链接
片段表达式 ~{..} 引入公共页面

字面量

文本值: 'one text' , 'Another one!' ,…数字: 0 , 34 , 3.0 , 12.3 ,…布尔值: true , false

空值: null

变量: one,two,.... 变量不能有空格

文本操作

字符串拼接:+

变量替换:|The name is ${name}|

数学运算

运算符: + , - , * , / , %

布尔运算

运算符:and ,or

一元运算:!,not

比较运算

比较: > , < , >= , <= ( gt , lt , ge , le )等式: == , != ( eq , ne )

条件运算

If-then: (if) ? (then)

If-then-else: (if) ? (then) : (else)

Default: (value) ?: (defaultvalue)

特殊操作

无操作: _

设置属性值

设置单个值

<form action="subscribe.html" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  </fieldset>
</form>

设置多个值

<img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

以上两个的代替写法 th:xxxx

<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
<form action="subscribe.html" th:action="@{/subscribe}">

迭代(循环)

<tr th:each="prod : ${prods}">
        <td th:text="${prod.name}">Onions</td>
        <td th:text="${prod.price}">2.41</td>
        <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
  <td th:text="${prod.name}">Onions</td>
  <td th:text="${prod.price}">2.41</td>
  <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

条件运算

<a href="comments.html"
th:href="@{/product/comments(prodId=${prod.id})}"
th:if="${not #lists.isEmpty(prod.comments)}">view</a>
<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

名称空间

只有在html页面中引入了名称空间,才可以使用Thymemeaf的语法提示

<html lang="en" xmlns:th="http://www.thymeleaf.org">

属性的优先级

image.png

在SpringBoot里面使用

引入Starter

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

自动配置好了thymeleaf

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration { }

自动配好的策略

  1. 所有thymeleaf的配置值都在 ThymeleafProperties
  2. 配置好了 SpringTemplateEngine
  3. 配好了 ThymeleafViewResolver
  4. 我们只需要直接开发页面
	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";  //xxx.html

页面开发

html代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}">哈哈</h1>
<h2>
    <a href="www.atguigu.com" th:href="${link}">去百度</a>  <br/>
    <a href="www.atguigu.com" th:href="@{link}">去百度2</a>
</h2>
</body>
</html>

java代码

@Controller
public class ViewController {
    @GetMapping("/hello")
    public String hello( Model model){
        model.addAttribute("msg","你好,世界");
        model.addAttribute("link","http://www.baidu.com");
        return "succes";
    }
}

Thymemeaf的进阶使用

配置前置路径

配置好后所有的请求必须以/lxs开头,最好别用,加了老忘

server:
  servlet:
    context-path: /lxs

解决重复提交页面

假如要从登录页跳转到展示页面,如果是转发,页面刷新会引发重复提交表单数据的问题,针对这种问题,可以使用重定向来解决。

  1. 我们可以创建一个专门去展示页面的请求
@GetMapping("/main")
public String main(){
	return "main";
}

2.改变登录请求,从转发变成重定向到main请求,由main请求完成跳转功能

@PostMapping("/login")
public String login(String username,String password){
	
    //重定向到main请求
    return "redirect:/main"
}

SpringMVC扩展:设置多个请求访问同一个方法

value可以是数组

@GetMapping(value = {"/","/login"})

抽取公共片段

概念:将页面中重复的元素提取出来,单独放到一个html中,其他页面引用这个html,这就是抽取公共片段

  1. 在公共页面的标签中加入 th:fragment="copy"

    <div th:fragment="copy">
    &copy; 2011 The Good Thymes Virtual Grocery
    </div>
    

    也可以使用id选择器

    <div id="copy">
    &copy; 2011 The Good Thymes Virtual Grocery
    </div>
    
  2. 引入公共片段

    <div th:insert="~{footer :: copy}"></div>
    ~{templatename::#selector}:模板名::选择器 <!-- 如果是id选择器,在选择器名前面要加入#,其他选择器同理 -->
    ~{templatename::fragmentname}:模板名::片段名
    

    注:模板名就是html文件的名称,选择器就是id的值,片段名就是th:fragment的值

  3. 默认效果

    insert的公共片段在div标签中

    如果使用th:insert等属性进行引入,可以不用写~{}:

    行内写法可以加上:[[{}]];[({})];

三种引入公共片段的th属性:

th:insert:将公共片段整个插入到声明引入的元素中

th:replace:将声明引入的元素替换为公共片段

th:include:将被引入的片段的内容包含进这个标签中

<footer th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</footer>

引入方式
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>

效果
<div>
    <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
</div>

<footer>
&copy; 2011 The Good Thymes Virtual Grocery
</footer>

<div>
&copy; 2011 The Good Thymes Virtual Grocery
</div>

引入片段的时候传入参数:

<!--引入公共片段;传入参数-->
<div th:insert="~{common :: #cc(a='abc')}"></div>
<!-- 公共页面中任何属性都可以使用传递过来的参数,用${}接收 -->
<div id="cc" th:name="${a}">测试</div>

Thymeleaf 内置对象

日期和字符串处理

注意语法:

​ 1,调用内置对象一定要用#

​ 2,大部分的内置对象都以 s 结尾 strings、numbers、dates

日期处理:

<input type="text" name="birth" th:value="${#dates.format(birth,'yyyy-MM-dd')}"/>

字符串处理:

<input type="text" name="msg" th:value="${#strings.substring(msg,0,6)}"/>
我等的船还不来
原文地址:https://www.cnblogs.com/lxs1204/p/14274290.html