最先开发的时候,展现页面咱们都是使用HTML完成咱们的代码编写;可是咱们的显示页面必定是须要动态变化的,以后就引入了Jsp技术,用来进行数据的显示及交互,可是Jsp是以war包进行部署,可是以后想用jar包的方式打包,这种方式就会很麻烦,因此就有了模板引擎技术 ,模板引擎有不少,好比jsp,freemarker,thymeleaf等,咱们用thymeleaf来举例html
官网地址:https://www.thymeleaf.org/java
github地址:https://github.com/thymeleaf/thymeleafgit
中文网站:https://raledong.gitbooks.io/using-thymeleaf/content/github
先引入依赖,我用SpringBoot的starterspring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
在springboot中有专门的thymeleaf配置类:ThymeleafProperties数组
@ConfigurationProperties(prefix = "spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; /** * Whether to check that the template exists before rendering it. */ private boolean checkTemplate = true; ..................................
@Controller public class RequestController { @GetMapping("/request") public String request(Model model){ model.addAttribute("msg","name"); return "show"; } }
<!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> </body> </html>
表达式名字 | 语法 | 用途 |
---|---|---|
变量取值 | ${...} | 获取请求域、session域、对象等值 |
选择变量 | *{...} | 获取上下文对象值 |
消息表达式 | #{...} | 获取国际化等值 |
连接URL | @{...} | 生成连接 |
片断表达式 | ~{...} | 同jsp:include 做用,引入公共页面片断 |
'one text'
, 'Another one!'
,…0
, 34
, 3.0
, 12.3
,…true
, false
null
one
, sometext
, main
,…+
|The name is ${name}|
+
, -
, *
, /
, %
and
, or
!
, not
>
, <
, >=
, <=
(gt
, lt
, ge
, le
)==
, !=
(eq
, ne
)(if) ? (then)
(if) ? (then) : (else)
(value) ?: (defaultvalue)
_
th:text/ th:utext :设置当前元素的文本内容,二者的区别在于前者不会转义html标签,后者会。优先级不高:order=7springboot
th:value/ th:src/ th:href:设置当前元素的value值,优先级不高:order=6session
th:each:遍历循环元素,和th:text或th:value一块儿使用。注意该属性修饰的标签位置,详细日后看。优先级很高:order=2app
th:if:条件判断,相似的还有th:unless,th:switch,th:case。优先级较高:order=3less
th:insert/ th:include/ th:replace:代码块引入,三者的区别较大,经常使用于公共代码块提取的场景。优先级最高:order=1
th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8
th:object:声明变量,通常和*{}一块儿配合使用,达到偷懒的效果。优先级通常:order=4
th:attr/ th:attrappend/ th:attrprepend:修改任意属性优先级通常:order=5
全部h5兼容的标签写法:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes
关于属性的优先级
此外thymeleaf有不少内置方法,与Java的API相似!
strings:字符串格式化方法,经常使用的Java方法它都有。好比:equals,length,trim,toUpperCase,indexOf等
numbers:数值格式化方法,经常使用的方法有:formatDecimal等
bools:布尔方法,经常使用的方法有:isTrue,isFalse等
arrays:数组方法,经常使用的方法有:toArray,length,isEmpty,contains,containsAll等
lists,sets:集合方法,经常使用的方法有:toList,size,isEmpty,contains,containsAll,sort等
maps:对象方法,经常使用的方法有:size,isEmpty,containsKey,containsValue等
dates:日期方法,经常使用的方法有:format,year,month,hour,createNow等