Thymeleaf模板引擎

更多配置参考官方文档:https://www.thymeleaf.org/documentation.html

中文参考手册:https://www.lanzous.com/i7dzr2j

Thymeleaf语法

常用标签

在HTML页面上使用Thymeleaf标签,Thymeleaf 标签能够动态地替换掉静态内容,使页面动态展示。
为了大家更直观的认识Thymeleaf,下面展示一个在HTML文件中嵌入了Thymeleaf的页面文件
示例代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" media="all" 	
              href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
        <title>Title</title>
    </head>
    <body>
        <p th:text="${hello}">欢迎进入Thymeleaf的学习</p>
    </body>
</html>

上述代码中,xmlns:th="http://www.thymeleaf.org"用于引入Thymeleaf模板引擎标签,
使用关键字th标注标签是Thymeleaf模板提供的标签,
其中,th:href用于引入外联样式文件,th:text用于动态显示标签文本内容。

除此之外,Thymeleaf模板提供了很多标签,接下来,通过一张表罗列Thymeleaf的常用标签

th:标签说明
th:insert布局标签,替换内容到引入的文件
th:replace页面片段包含(类似JSP中的include标签)
th:each元素遍历(类似JSP中的c:forEach标签)
th:if条件判断,如果为真
th:unless条件判断,如果为假
th:switch条件判断,进行选择性匹配
th:case条件判断,进行选择性匹配
th:value属性值修改,指定标签属性值
th:href用于设定链接地址
th:src用于设定链接地址
th:text用于指定标签显示的文本内容

标准表达式

说明表达式语法
变量表达式${…}
选择变量表达式*{…}
消息表达式#{…}
链接URL表达式@{…}
片段表达式~{…}

1.变量表达式 ${...}
变量表达式${…}主要用于获取上下文中的变量值,示例代码如下:

<p th:text="${title}">这是标题</p>

示例使用了Thymeleaf模板的变量表达式${…}用来动态获取P标签中的内容,如果当前程序没有启动或
者当前上下文中不存在title变量,该片段会显示标签默认值“这是标题”;如果当前上下文中存在title变量
并且程序已经启动,当前P标签中的默认文本内容将会被title变量的值所替换,从而达到模板引擎页面
数据动态替换的效果

同时,Thymeleaf为变量所在域提供了一些内置对象,具体如下所示

# ctx:上下文对象
# vars:上下文变量
# locale:上下文区域设置
# request:(仅限Web Context)HttpServletRequest对象
# response:(仅限Web Context)HttpServletResponse对象
# session:(仅限Web Context)HttpSession对象
# servletContext:(仅限Web Context)ServletContext对象

结合上述内置对象的说明,假设要在Thymeleaf模板引擎页面中动态获取当前国家信息,可以使用#locale内置对象,
示例代码如下

The locale country is: <span th:text="${#locale.country}">US</span>.

上述代码中,使用th:text="${#locale.country}"动态获取当前用户所在国家信息,其中标签内默认
内容为US(美国),程序启动后通过浏览器查看当前页面时,Thymeleaf会通过浏览器语言设置来识别
当前用户所在国家信息,从而实现动态替换

2.选择变量表达式 *{...}

选择变量表达式和变量表达式用法类似,一般用于从被选定对象而不是上下文中获取属性值,如
果没有选定对象,则和变量表达式一样,示例代码如下

<div th:object="${book}">
	<p>titile: <span th:text="*{title}">标题</span>.</p>
</div>

3.消息表达式 #{...}

消息表达式#{…}主要用于Thymeleaf模板页面国际化内容的动态替换和展示,
使用消息表达式#{…}进行国际化设置时,还需要提供一些国际化配置文件。
关于消息表达式的使用,后续会详细说明

4.链接表达式@{...}

链接表达式@{…}一般用于页面跳转或者资源的引入,在Web开发中占据着非常重要的地位,
并且使用也非常频繁,示例代码如下:

<a th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">view</a>
<a th:href="@{/order/details(orderId=${o.id})}">view</a>

上述代码中,链接表达式@{…}分别编写了绝对链接地址和相对链接地址。
在有参表达式中,需要按照@{路径(参数名称=参数值,参数名称=参数值…)}的形式编写,
同时该参数的值可以使用变量表达式来传递动态参数值

5.片段表达式~{...}

片段表达式~{…}用来标记一个片段模板,并根据需要移动或传递给其他模板。其中,最常见的用法是使
用th:insert或th:replace属性插入片段,示例代码如下:

<div th:insert="~{thymeleafDemo::title}"></div>

标签中。thymeleafDemo为模板名称,
Thymeleaf会自动查找“/resources/templates/”目录下的thymeleafDemo模板,title为片段名称
上述代码中,使用th:insert属性将title片段模板引用到该

Thymeleaf使用

  1. 首先 在Spring Boot项目中使用Thymeleaf模板,首先必须保证引入Thymeleaf依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
  1. 其次,在全局配置文件中配置Thymeleaf模板的一些参数。一般Web项目都会使用下列配置,示例代码如下
spring.thymeleaf.cache = true #启用模板缓存
spring.thymeleaf.encoding = UTF-8 #模板编码
spring.thymeleaf.mode = HTML5 #应用于模板的模板模式
spring.thymeleaf.prefix = classpath:/templates/ #指定模板页面存放路径
spring.thymeleaf.suffix = .html #指定模板页面名称的后缀

上述配置中,spring.thymeleaf.cache表示是否开启Thymeleaf模板缓存,默认为true,
在开发过程中通常会关闭缓存,保证项目调试过程中数据能够及时响应;
spring.thymeleaf.prefix指定了Thymeleaf模板页面的存放路径,默认为classpath:/templates/;
spring.thymeleaf.suffix指定了Thymeleaf模板页面的名称后缀,默认为.html

  1. 静态资源的访问

开发Web应用时,难免需要使用静态资源。Spring boot默认设置了静态资源的访问路径。
使用Spring Initializr方式创建的Spring Boot项目,默认生成了一个resources目录,在resources目录
中新建public、resources、static三个子目录下,Spring boot默认会挨个从public、resources、static
里面查找静态资源

  1. 案例
@Controller
public class LoginController {
    /**
    * 获取并封装当前年份跳转到登录页login.html
    */
    @RequestMapping("/toLoginPage")
    public String toLoginPage(Model model){
        model.addAttribute("currentYear",
        Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }
}    

toLoginPage()方法用于向登录页面login.html跳转,同时携带了当前年份信息currentYear。

在“classpath:/templates/”目录下引入一个用户登录的模板页面login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1,shrinkto-fit=no">
        <title>用户登录界面</title>
        <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
        <link th:href="@{/login/css/signin.css}" rel="stylesheet">
    </head>
    <body class="text-center">
        <!-- 用户登录form表单 -->
        <form class="form-signin">
            <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
            <h1 class="h3 mb-3 font-weight-normal">请登录</h1>
            <input type="text" class="form-control"  th:placeholder="用户名" required="" autofocus="">
            <input type="password" class="form-control" th:placeholder="密码" required="">
            <div class="checkbox mb-3">
                <label>
                	<input type="checkbox" value="remember-me"> 记住我
                </label>
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit" >登录</button>
            <p class="mt-5 mb-3 text-muted"> © 
                <span  th:text="${currentYear}">2019
                	</span>-<span th:text="${currentYear}+1">2020
                </span>
            </p>
        </form>
    </body>
</html>

通过xmlns:th="http://www.thymeleaf.org"引入了Thymeleaf模板标签;
使用th:hrefth:src分别引入了两个外联的样式文件和一个图片;
使用th:text引入了后台动态传递过来的当前年份currentYear

配置国际化页面

编写多语言国际化配置文件

在项目的类路径resources下创建名称为i18n的文件夹,并在该文件夹中根据需要编写对应的多语言国际化文件
login.properties、login_zh_CN.properties和login_en_US.properties文件

login.properties

login.tip=请登录
login.username=用户名
login.password=密码
login.rememberme=记住我
login.button=登录

login_zh_CN.properties

login.tip=请登录
login.username=用户名
login.password=密码
login.rememberme=记住我
login.button=登录

login_en_US.properties

login.tip=Please sign in
login.username=Username
login.password=Password
login.rememberme=Remember me
login.button=Login

login.properties为自定义默认语言配置文件,
login_zh_CN.properties为自定义中文国际化文
件,login_en_US.properties为自定义英文国际化文件

需要说明的是,Spring Boot默认识别的语言配置文件为类路径resources下的messages.properties;
其他语言国际化文件的名称必须严格按照“文件前缀名语言代码国家代码.properties”的形式命名

本示例中,在项目类路径resources下自定义了一个i18n包用于统一配置管理多语言配置文件,并
将项目默认语言配置文件名自定义为login.properties,因此,后续还必须在项目全局配置文件中进行
国际化文件基础名配置,才能引用自定义国际化文件

编写配置文件

打开项目的application.properties全局配置文件,在该文件中添加国际化文件基础名设置

# 配置国际化文件基础名
spring.messages.basename=i18n.login

spring.messages.basename=i18n.login设置了自定义国际化文件的基础名。
其中,i18n表示国际化文件相对项目类路径resources的位置,login表示多语言文件的前缀名。

如果配置文件中没有配置基础名,就在类路径下找基础名为message的配置文件

如果开发者完全按照Spring Boot默认识别机制,
在项目类路径resources下编写messages.properties等国际化文件,可以省略国际化文件基础名的配置

定制区域信息解析器

在完成上一步中多语言国际化文件的编写和配置后,就可以正式在前端页面中结合Thymeleaf模板
相关属性进行国际化语言设置和展示了,不过这种实现方式默认是使用请求头中的语言信息(浏览器语
言信息)自动进行语言切换的,有些项目还会提供手动语言切换的功能,这就需要定制区域解析器了

@Configuration
public class MyLocaleResovel implements LocaleResolver {
    // 自定义区域解析方式
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        // 获取页面手动切换传递的语言参数l
        String l = httpServletRequest.getParameter("l");
        // 获取请求头自动传递的语言参数Accept-Language
        String header = httpServletRequest.getHeader("Accept-Language");
        Locale locale=null;
        // 如果手动切换参数不为空,就根据手动参数进行语言切换,否则默认根据请求头信息切换
        if(!StringUtils.isEmpty(l)){
            String[] split = l.split("_");
            locale=new Locale(split[0],split[1]);
        }else {
            // Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
            String[] splits = header.split(",");
            String[] split = splits[0].split("-");
            locale=new Locale(split[0],split[1]);
        } 
        return locale;
    } 
    
    @Override
    public void setLocale(HttpServletRequest httpServletRequest, 
                          @Nullable HttpServletResponse httpServletResponse, 
                          @Nullable Locale locale) {
    } 
    
    // 将自定义的MyLocalResovel类重新注册为一个类型LocaleResolver的Bean组件
    @Bean
    public LocaleResolver localeResolver(){
   	 return new MyLocalResovel();
    }
}

页面国际化使用

打开项目templates模板文件夹中的用户登录页面login.html,结合Thymeleaf模板引擎实现国际化功能
将页面文字改为获取国际化配置,格式#{key}

<
!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,shrinkto-fit=no">
    <title>用户登录界面</title>
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
    <!-- 用户登录form表单 -->
    <form class="form-signin">
        <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
        <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">请登录</h1>
        <input type="text" class="form-control" th:placeholder="#{login.username}" >
        <input type="password" class="form-control" th:placeholder="#{login.password}">
        <div class="checkbox mb-3">
            <label>
            	<input type="checkbox" value="remember-me"> [[#{login.rememberme}]]
            </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" 
                type="submit" th:text="#{login.button}">登录</button>
        
        <p class="mt-5 mb-3 text-muted">© 
            <span th:text="${currentYear}">2018
                </span>-<span th:text="${currentYear}+1">2019
            </span>
        </p>
        
        <a class="btn btn-sm" th:href="@{/toLoginPage(l='zh_CN')}">中文</a>
        <a class="btn btn-sm" th:href="@{/toLoginPage(l='en_US')}">English</a>
    </form>
</body>
</html>

在表单尾部提供了中文、English手动切换语言的功能链接,在单击链接时会通过后台定制的区域解析器进行手动语言切换

thymeleaf公共页面元素抽取

在我们的模板中,经常会出现许多重复部分,例如页脚,页眉,菜单等部分。

为此,Thymeleaf需要我们定义这些重复的“片段”,可以使用该th:fragment属性来完成。

假设我们要在所有杂货店页面中添加标准的版权页脚,因此我们创建一个/WEB-INF/templates/footer.html包含以下代码的文件:

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

  <body>
  
    <div th:fragment="copy">
      &copy; 2011 The Good Thymes Virtual Grocery
    </div>
  
  </body>
  
</html>

我们可以使用th:insertth:replace属性之一轻松地将其包含在主页中

<body>

  ...

  <div th:insert="~{footer :: copy}"></div>
  <!-- ~{} 可省略-->  
  <div th:insert="footer :: copy"></div>
  
</body>

如果引用片段不带 th:fragment

...
<div id="copy-section">
  &copy; 2011 The Good Thymes Virtual Grocery
</div>
...

我们可以通过其id属性引用它,类似于CSS选择器:

<body>

  ...

  <div th:insert="~{footer :: #copy-section}"></div>
  
</body>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值