SpringBoot专栏_web:模板引擎Thymeleaf使用实战,图文结合附带源码下载(第7讲)

版权声明:更多信息请关注 wwws.shinians.com 官网 https://blog.csdn.net/zzhuan_1/article/details/85215289

简介:

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,
Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成
作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够
直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用
Spring Boot推荐使用Thymeleaf。

模板引擎语言有JSP、Velocity、Freemarker、Thymeleaf,由于Thymeleaf语法简单,功能强大,SpringBoot推荐使用。

Thymeleaf如何使用

HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
 

1、导入thymeleaf的名称空间

1、导入thymeleaf的名称空间

2、使用thymeleaf语法;

基本语法

• 表达式:
– #{...}:国际化消息
– ${…}:变量取值
– *{…}:当前对象/变量取值
– @{…}:url表达式
– ~{…}:片段引用
– 内置对象/共用对象:
• 判断/遍历:
– th:if
– th:unless
– th:each
– th:switch、th:case
• th:属性

项目实战:

现在大多项目实现前后端分离虽然模板语言使用会有所减少,但是做小项目的时候还是很有用的,可以简单了解下语法。

1.初步配置

配置文件配置缓存关闭,不然开发总是重启

#thymeleaf start
  thymeleaf:
    mode: HTML
    encoding: UTF-8
    content-type: text/html
    cache: false

2.如何定义公用头和footer

我们以框架项目为例吧,里面继承了而很多技术,包括以后案例讲解都会从中挑取代码,所以感兴趣的可以提前了解下。

common中定义了头和尾的共有引入文件。

sys_header_m1.html

其中要注意th:fragment、th:block和th:replace的用法

<head th:fragment="sys_header(title,links,scripts)">

<title th:replace="${title}">limp-framework title</title>

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head th:fragment="sys_header(title,links,scripts)">
    <!--fragment标签,这个类是JSP的tag:在多个地方出现的元素块用fragment包起来,在需要的地方,可以用th:include或者th:replace进行带入-->
    <meta charset="utf-8">
    <title th:replace="${title}">limp-framework title</title>

    <!--全局通用框架样式 begin-->

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!--引入Theme style 样式-->
    <link rel="stylesheet" type="text/css" th:href="@{/systemsite/assets/static/css/font.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/systemsite/assets/static/css/limpframwork.css}"/>


   
    <!--全局通用框架样式 end-->

    <!--/* Per-page placeholder for additional links */-->
    <th:block th:replace="${links}" />
    <!--/* Per-page placeholder for additional styles */-->
    <th:block th:replace="${scripts}" />


</head>

sys_footer_m1.html

其它页面如何引入?引入head和footer

引入footer

<div th:replace="systemsite/m1/pages/common/sys_footer_m1 :: sys_footer"></div>

END

现在项目异步渲染的比较多,所以简单了解下基本使用即可。(生成html静态页面的时候可能会使用到)

猜你喜欢

转载自blog.csdn.net/zzhuan_1/article/details/85215289