demo:https://download.csdn.net/download/lemonmr/12517009
- 模板引擎thymeleaf
1.1 thymeleaf简介
Thymeleaf是一个适用于Web和独立环境的现代服务器端Java模板引擎。
Thymeleaf 的主要目标是为您的开发工作流程带来优雅的自然模板 - 可以在浏览器中正确
显示的HTML,也可以用作静态原型,从而在开发团队中实现更强大的协作。
通过Spring Framework模块,与您喜欢的工具的大量集成,以及插入您自己的功能的能
力,Thymeleaf是现代HTML5 JVM Web开发的理想选择 - 尽管它可以做得更多。
官网:https://www.thymeleaf.org/
官方文
档:https://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#preface
1.2 为什么要使用thymeleaf
1.2.1 thymeleaf PK Vue.js
我们在前期课程中已经讲解了vue.js这样的前端框架,为什么我们还要在项目中使用
thymeleaf ? 首先说这两种技术本质上属于不同类型的产品。vue.js属于前端框架,而
thymeleaf 属于模板引擎。虽然它们可以实现相同的功能(比如一个列表),但是它们的
工作过程却是不同: vue.js通过异步方式请求数据,后端给前端返回json,前端通过
vue指令循环渲染列表。thymeleaf 则是在后端实现页面的渲染,将渲染后的页面直接给
浏览器展示。
那什么时候使用vue.js,什么使用thymeleaf 呢?一般来说,管理后台我们会使用前
端框架,而网站前台的部分有些页面会使用thymeleaf。原因有两点:
(1)因为使用vue.js由于是异步请求,从页面打开到信息的展示会出现延迟,而使
用thymeleaf,页面打开会立刻看到页面的信息。
(2)异步加载的数据不会被搜索引擎抓取。所以当我们希望数据被搜索引擎收录,
就需要使用thymeleaf这样的模板引擎。
1.2.2 thymeleaf PK JSP
有同学会问,thymeleaf 目前所作的工作和jsp有相似之处。没错,thymeleaf和jsp
都是属于服务端渲染技术。thymeleaf比jsp功能强大许多,它的强大已经超出你的想
象。我们在此项目后会学习一个新的框架叫spring boot ,thymeleaf就是spring boot 官
方推荐使用的模板引擎。
1.3 thymeleaf快速入门
1.3.1 最简单案例
(1)创建测试工程,引入依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
(2)创建模板。在resources目录下创建test.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF‐8">
<title>thymeleaf入门demo</title>
</head>
<body>
<span th:text="${name}"></span>
</body>
</html>
(3)创建测试类,编写代码
// 1.上下文
Context context = new Context();
//创建数据模型
Map<String, Object> dataModel =new HashMap();
dataModel.put("name","青橙电商系统");
context.setVariables(dataModel);
// 2.准备文件
File dest = new File("d:/test_out.html");
// 3.生成页面
try {
PrintWriter writer = new PrintWriter(dest, "UTF‐8");
ClassLoaderTemplateResolver resolver = new
ClassLoaderTemplateResolver();//模板解析器
resolver.setTemplateMode(TemplateMode.HTML);//模板模型
resolver.setSuffix(".html");//后缀
TemplateEngine engine = new TemplateEngine();//创建模板引擎
engine.setTemplateResolver(resolver);//设置模板解析器
engine.process("test", context, writer);//执行模板引擎
} catch (Exception e) {
e.printStackTrace();
}
1.3.2 常用th标签
========================================================
thymeleaf 常用小技巧
小数处理
<em th:text="${#numbers.formatDecimal(sku.price/100,0,2)}"></em>
#numbers.formatDecimal(numbwe, 整数位,小数位) 。
注意:指定整数位不为0,表示位数不足用0补齐,
例: #numbers.formatDecimal(3.456,2,2) 结果为 03.45
对图片操作使用utext
<div class="intro-detail" th:utext="${sku.introduction}">
</div>
等同
<div class="intro-detail">
<img src="./img/_/intro01.png" />
<img src="./img/_/intro02.png" />
<img src="./img/_/intro03.png" />
</div>
map集合如何循环取值
<!--规格列表-->
<ul class="goods-intro unstyled">
<li th:each="spec:${specItems}" th:text="${spec.key+':'+spec.value}" ></li>
</ul>