模板引擎--Thymeleaf

时间:2020-05-30
本文章向大家介绍模板引擎--Thymeleaf,主要包括模板引擎--Thymeleaf使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

模板引擎Thymeleaf

模板引擎思想

SpringBoot推荐的Thymeleaf(语法更简单,功能更强大)

1.引入Thymeleaf

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

Thymeleaf 3 和 layout 2 是一个适配

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";
    static {
        DEFAULT_ENCODING = StandardCharsets.UTF_8;
    }

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

使用:

  1. 导入thymeleaf的名称空间

    <html xmlns:th="http://www.thymeleaf.org">
    
  2. 使用thymeleaf语法:

    <body>
    <h1>成功!~</h1>
        <!--  th:text 将div里边的文本内容设置为;而且会替换原本div内部的文字 -->
        <div th:text="${hello}">这是显示欢迎信息</div>
    </body>
    

3. 语法规则

1.th: --- 改变当前元素里面的内容

​ th:任意html属性:可以覆盖任意的值 例如: th:id="${hello}" ==> id="hello"

FEATURE ATTRIBUTES mean
Fragment inclusion th:insert th:replace 片段包含
Fragment iteration th:each 遍历
Conditional evaluation th:if th:unless th:switch th:case 条件判断
Local variable definition th:object th:with 声明变量
General attribute modification th:attr th:attrprepend th:attrappend 任意属性修改支持append prepend
Specific attribute modification th:value th:href th:src 修改指定属性默认值
Text (tag body modification) th:text(转义特殊字符) th:utext(不转义) 修改标签体内容
Fragment specification th:fragment 声明片段
Fragment removal th:remove 移除

2.表达式

Simple expressions:(表达式语法)
	- Variable Expressions: ${...}   获取变量值;OGNL;
		1. 获取对象的属性,调用方法
		2. 使用内置基本对象
			#ctx : the context object.
			#vars: the context variables.
			#locale : the context locale.
			#request : (only in Web Contexts) the HttpServletRequest object.
			#response : (only in Web Contexts) the HttpServletResponse object.
			#session : (only in Web Contexts) the HttpSession object.
			#servletContext : (only in Web Contexts) the ServletContext object
		3.内置的一些工具对象
            #execInfo : information about the template being processed.
            #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
            #uris : methods for escaping parts of URLs/URIs6
            #conversions : methods for executing the configured conversion service (if any).
            #dates : methods for java.util.Date objects: formatting, component extraction, etc.
            #calendars : analogous to #dates , but for java.util.Calendar objects.
            #numbers : methods for formatting numeric objects.
            #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
            #objects : methods for objects in general.
            #bools : methods for boolean evaluation.
            #arrays : methods for arrays.
            #lists : methods for lists.
            #sets : methods for sets.
            #maps : methods for maps.
            #aggregates : methods for creating aggregates on arrays or collections.
            #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
	- Selection Variable Expressions: *{...}  选择表达式:
		#1. 和${}在功能上是一样
		#2. 配合th:object进行使用的:取出对象中的属性
		<div th:object="${session.user}">
			<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
			<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
			<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
		</div>
	- Message Expressions: #{...}   
		# 获取国际化内容
	- Link URL Expressions: @{...}
		# 括住超链接,可以在其中加入${}实现动态链接
		<a href="order/list.html" th:href="@{/order/list}">Order List</a>
	- Fragment Expressions: ~{...}
		1.片段引用表达式<div th:insert="~{commons :: main}">...</div>
		

3.简单示例

<h1>成功!~</h1>
    <!--  th:text 将div里边的文本内容设置为;而且会替换原本div内部的文字 -->
    <div th:text="${hello}" id="hello" >这是显示欢迎信息</div>
    <div th:text="${hello}" >这是显示欢迎信息</div>
    <div th:utext="${hello}" >这是显示欢迎信息</div>

<hr/>

<!--th:each每次遍历都会生成当前这个标签-->
<h4 th:text="${user}" th:each="user : ${users}"></h4>

<hr/>
<h4>
    <span  th:each="user : ${users}">[[${user}]]</span>
</h4>

4.抽取公共片段

  1. 抽取片段

    <div th:fragment = "copy" id="common">
        ........
    </div>
    
  2. 引入公共片段

    模板名会使用thymeleaf的前后缀配置规则进行解析,没有就是页面的抽取片段存在的页面名

    <div th:insert="~{footer :: copy}"></div>
    
    ~{templatename::fragmentname}: 模板名::片段名  以上为这种
    <div th:insert="~{footer::#common}"></div>
    ~{templatename::selector} : 模板名::选择器
    
    默认效果:如果insert的功能片段在div中,使用th:insert引入可以不用~{}
    行内写法加上:[[~{}]];[(~{})]
    
  3. 不同引入效果:

    insert的功能片段在div标签中

    <footer th:fragment="copy">
    	&copy; 2011 The Good Thymes Virtual Grocery
    </footer>
    
    <body>
    ...
    <div th:insert="footer :: copy"></div>    将整个声明片段插入到引用元素中
    <div th:replace="footer :: copy"></div>	   替换为公共片段,不包含当前div
    <div th:include="footer :: copy"></div>		将被引入的片段内容包含进这个标签中
    </body>
    
    <body>
    ...
    <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>
    </body>
    
  4. 公共片段抽取引入的参数传递

    抽取片段时候定义变量,引入时,对应获取

    <div th:fragment="frag (onevar,twovar)"> 
       <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
    </div>
    
    <div th:replace="::frag (${value1},${value2})">...</div>
    
    

    直接在引入的时候定义变量名以及值

    <div th:replace="::frag (onevar=${value1},twovar=${value2})">...</div>
    

原文地址:https://www.cnblogs.com/JIATCODE/p/12994016.html