Thymeleaf 高级语言模板引擎

一、模板引擎
  1. 类型
    JSP、Velocity、Freemarker、Thymeleaf
  2. 实现思想
二、Thymeleaf 高级语言模板引擎

(1)引入Thymeleaf

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<properties>
    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    //布局功能支持的程序 thymeleaf3主程序 layout2以上版本
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>

(2)Thymeleaf 使用&语法

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
}

(3)尝试

@RequestMapping("/success")
public String success(){
	//返回classpath:/templates/success.html
	return "success";
}

只要我们把HTML页面放在 classpath:/templates/ ,Thymeleaf 就能自动渲染:
使用:

  • 导入themeleaf的名称空间
<html lang="en" xmlns:th="https://www.thymeleaf.org">
  • 使用thymeleaf 语法
//修改标签体内容(转义特殊字符)
<div th:text="${hello}"></div>
//不转义
<div th:utext="${hello}"></div>
//th:each每次便利都会生成当前标签
//3个H4
<h4 th:text="${user}" th:each="user:${users}"></h4>
//一个H4内3个span
<h4><span th:each="user:${users}"></span></h4>
//行内元素
[[]]	//th:text
[()]	//th:utext

① th: 功能标签:任意html属性替换原生属性

② 表达式语法:

Simple expressions:
	Variable Expressions: ${...}	//获取对象的属性;调用方法;使用内置对象,内置以下工具类。
	Selection Variable Expressions: *{...}		//选择表达式
	Message Expressions: #{...}		//获取国际化内容
	Link URL Expressions: @{...}		//定义URL
	Fragment Expressions: ~{...}		//片段引用表达式
Literals:		//字面量
	Text literals: 'one text' , 'Another one!' ,…
	Number literals: 0 , 34 , 3.0 , 12.3 ,…
	Boolean literals: true , false
	Null literal: null
	Literal tokens: one , sometext , main ,…
Text operations:	//文本操作
	String concatenation: +
	Literal substitutions: |The name is ${name}|
Arithmetic operations:		//数字运算
	Binary operators: + , - , * , / , %
	Minus sign (unary operator): -
Boolean operations:			//布尔运算
	Binary operators: and , or
	Boolean negation (unary operator): ! , not
Comparisons and equality:		//比较运算
	Comparators: > , < , >= , <= ( gt , lt , ge , le )
	Equality operators: == , != ( eq , ne )
Conditional operators:		//条件运算
	If-then: (if) ? (then)
	If-then-else: (if) ? (then) : (else)
	Default: (value) ?: (defaultvalue)
Special tokens:
	No-Operation: _

点击查看 更多Thymeleaf 语法。

你可能感兴趣的:(框架)