05-02-SpringBoot之thymeleaf模板引擎使用

thymeleaf模板引擎使用

一、简介

模板引擎:将一些数据通过模板引擎渲染到到页面中,模板引擎存在于服务器,当客户端请求页面时,模板引擎会将作用域中的数据动态地渲染到页面中,这里需要注意的是只有针对于前后端不分离的项目才可以使用模板引擎(前后端分离项目中模板引擎只能获取到数据,但是无法拿到页面的信息)。

thymeleaf模板引擎:类似于JSP,能够在普通的页面的基础上,通过thymeleaf的语法将一些数据动态地渲染到页面上进行显示,同时thymeleaf是SpringBoot官方推荐的模板引擎。

二、Thymeleaf在SpringBoot中的自动配置

Thymeleaf默认自动配置解析

ThymeleafAutoConfiguration:
    @Bean
    SpringResourceTemplateResolver defaultTemplateResolver() {
     
       SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
       resolver.setApplicationContext(this.applicationContext);
       resolver.setPrefix(this.properties.getPrefix());
       resolver.setSuffix(this.properties.getSuffix());
       resolver.setTemplateMode(this.properties.getMode());
       if (this.properties.getEncoding() != null) {
     
          resolver.setCharacterEncoding(this.properties.getEncoding().name());
       }
       resolver.setCacheable(this.properties.isCache());
       Integer order = this.properties.getTemplateResolverOrder();
       if (order != null) {
     
          resolver.setOrder(order);
       }
       resolver.setCheckExistence(this.properties.isCheckTemplate());
       return resolver;
    }

@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;

	/**
	 * Whether to check that the templates location exists.
	 */
	private boolean checkTemplateLocation = true;

	/**
	 * Prefix that gets prepended to view names when building a URL.
	 */
	private String prefix = DEFAULT_PREFIX;

	/**
	 * Suffix that gets appended to view names when building a URL.
	 */
	private String suffix = DEFAULT_SUFFIX;

	/**
	 * Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
	 */
	private String mode = "HTML";

	/**
	 * Template files encoding.
	 */
	private Charset encoding = DEFAULT_ENCODING;

	/**
	 * Whether to enable template caching.
	 */
	private boolean cache = true;

在SpringBoot的对于Thymeleaf自动配置中,自动配置了一个默认的thymeleaf视图解析器(视图解析器是用于当控制器中返回一个页面名称时,视图解析器回去配置好的路径中寻找对应的页面资源,参考SpringMVC中的视图解析器),自动配置类中配置了这个默认的视图解析器的前缀、后缀等参数,而这些参数是从ThymeleafProperties这个配置类中获取的,我们可以看到ThymeleafProperties中配置了默认的前缀:classpath:/templates/、后缀:.html等,这相当于当我们返回一个视图名称(如success)时,这个thymeleaf的视图解析器会帮助我们将其映射到classpath:/templates/success.html文件。

Thymeleaf自定义配置

# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.cache=true # Whether to enable template caching.
spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists.
spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names (patterns allowed) that should be excluded from resolution.
spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.chunked-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set.
spring.thymeleaf.reactive.full-mode-view-names= # Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set.
spring.thymeleaf.reactive.max-chunk-size=0B # Maximum size of data buffers used for writing to the response.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.render-hidden-markers-before-checkboxes=false # Whether hidden form inputs acting as markers for checkboxes should be rendered before the checkbox element itself.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.servlet.produce-partial-output-while-processing=true # Whether Thymeleaf should start writing partial output as soon as possible or buffer until template processing is finished.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names (patterns allowed) that can be resolved.

注意:当我们处在开发环境时,需要将thymeleaf缓存关闭,如果开启,则加载一次模板后将会将其缓存,不再加载模板了,而开发环境会进行调试而修改html代码,如果开启缓存只能通过重启服务器达到刷新thymeleaf模板的作用。反之如果关闭了,在修改html页面之后可以通过ctrl+F9来进行重新编译。

三、搭建环境

1. 添加依赖


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<!-- 关闭thymeleaf缓存(修改application.yaml的内容) -->
spring:
  thymeleaf:
    cache: false

05-02-SpringBoot之thymeleaf模板引擎使用_第1张图片

2.在需要渲染的页面中导入命名空间

 xmlns:th="http://www.thymeleaf.org" 

05-02-SpringBoot之thymeleaf模板引擎使用_第2张图片

四、使用方法

在标签的属性前面加一个th:前缀

比如
<div th:text="${text}">div>

<div data-th-text="${text}">div>

五、常用方法

  • Simple expressions:(表达式语法)

    • Variable Expressions: ${...}获取变量值,用法与JSP中类似
    • Selection Variable Expressions: *{...}选择表达式
    • Message Expressions: #{...}获取国际化内容
    • Link URL Expressions: @{...}定义URL
    • Fragment Expressions: ~{...}片段(组件)引用表达式
  • Literals(文字)

    • Text literals: 'one text', 'Another one!',… 字符串型文字
    • Number literals: 0, 34, 3.0, 12.3,… 数字串型文字
    • Boolean literals: true, false 布尔型文字
    • Null literal: null null型文字
    • Literal tokens
  • Text operations:(文本操作)

    • + operator:
    • Literal substitutions: ----必须用( | )包裹
  • Arithmetic operations:(数学运算)

  • Binary operators: +, -div), *, /, %(mod)

  • Minus sign (unary operator): -

  • Boolean operations:(布尔运算)

    • Binary operators: and, or
    • Boolean negation (unary operator): !, not
  • Comparisons and equality:(比较运算)

    • Comparators: >, <, >=, <= (gt, lt, ge, le)
    • Equality operators: ==, != (eq, ne)
  • Conditional operators:条件运算(三元运算符)

    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)
  • Special tokens:

    • No-Operation: _

05-02-SpringBoot之thymeleaf模板引擎使用_第3张图片

1. 作用域中取值:${}、*{}


<div th:text="${text}">div>

<div th:text="${session.text}">div>

<div th:utext="${text}">div>

<div>[[text]]div>

<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastianspan>.p>
    <p>Surname: <span th:text="*{lastName}">Pepperspan>.p>
    <p>Nationality: <span th:text="*{nationality}">Saturnspan>.p>
div>
相当于
<div>
    <p>Name: <span th:text="${session.user.firstName}">Sebastianspan>.p>
    <p>Surname: <span th:text="${session.user.lastName}">Pepperspan>.p>
    <p>Nationality: <span th:text="${session.user.nationality}">Saturnspan>.p>
div>

2. 国际化#{}

获取properties中配置的信息,一般用于中英文的显示,比如英文的时候显示en_US.properties中配置的属性,而中文的时候显示zn_CN.properties中配置的属性

在home.properties中配置这个
home.welcome=this messages is from home.properties!
在html文件中

This text will not be show!

3. 超链接url表达式@{}

@{}= p a g e C o n t e x t . r e q u e s t . c o n t e x t P a t h 即 原 来 j s p 中 的 访 问 路 径 / {pageContext.request.contextPath}即原来jsp中的访问路径 / pageContext.request.contextPathjsp访/{pageContext.request.contextPath}/user==>@{/user}

4. if判断


<p th:text="${msg}" th:if="${not #strings.isEmpty(msg)}">p>


<td th:text="${user.getGender()==0?'':''}">td>

5. Switch–case

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administratorp>
  <p th:case="#{roles.manager}">User is a managerp>
  
  <p th:case="*">User is some other thingp>
div>

6. 循环


<div th:each="li:${list}" th:text="${li}">div>

<tr th:each="user:${userList}">
    <td th:text="${user.getId()}">td>
    <td th:text="${user.getUserName()}">td>
tr>

<tr data-th-each="user : ${users}">
    <td data-th-text="${user.login}">...td>
    <td data-th-text="${user.name}">...td>
tr>

7. 组件复用

将复用的代码提取出来


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


<div id="container" th:fragment="loginbar">
    <div id="output">
        <div class="containerT">
            <h1>用户登录h1>
            <form class="form" id="entry_form" th:action="@{/user/checkLogin}" method="post">
                <input name="username" type="text" placeholder="用户名" id="entry_name" value="admin">
                <input name="password" type="password" placeholder="密码" id="entry_password">
                <input type="submit" value="登录" class="entry_btn"/>
            form>
            <div>
                <a th:href="@{/user/register}" class="registA">立即注册--->a>
            div>
        div>
    div>
div>


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

html>

在复用的地方引入


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>组件复用测试title>
head>
    
	<div th:insert="~{commons/commons::loginbar}">div>
    
    <div th:replace="~{commons/commons::loginbar}">div>
    
    <div th:replace="commons/commons::frag (onevar=${value1},twovar=${value2})">...		div>
    <div th:replace="commons/commons::frag (onevar=${value1},twovar=${value2})">...		div>
body>
html>

如果要传递参数,可以使用()传参,接受后常进行判断

8. 单选框、复选框、下拉列表设置默认值


<input type="checkbox" name="option2" checked /> 
<input type="checkbox" name="option1" checked="checked" /> 

<input type="checkbox" name="active" th:checked="${user.active}" />

<input name="gender" type="radio" th:checked="${user.gender=='')}"><input name="gender" type="radio" th:checked="${user.gender==女')}">

<select id="computerLevel" name="computerLevel" class="valid">
    

9. Restful风格进行传参

前端页面

<a th:href="@{/user/toUpdate/{id}(id=${user.getId()})}">更新a>

控制器部分

    @GetMapping(value = "/toUpdate/{id}")
    public ModelAndView toUpdateUser(@PathVariable("id") String id){
     
        ModelAndView mv = new ModelAndView();
        User user = userService.findById(id);

        mv.addObject("user",user);

        mv.setViewName("user/user-edit");
        return mv;
    }

    /**
     * 用户信息更新
     **/
    @PostMapping(value = "/update")
    @ResponseBody
    public String updateUser(User user){
     
        if(userService.updateUserById(user)){
     
            return "success";
        }
        return "false";
    }

六、常用工具对象

地址:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects

05-02-SpringBoot之thymeleaf模板引擎使用_第4张图片

1.日期格式化


<td th:text="${#dates.format(user.getBirthdat(),'yyyy-MM-dd HH:mm:ss')}">td>

2.字符串操作



<p th:text="${msg}" th:if="${not #strings.isEmpty(msg)}">p>

你可能感兴趣的:(SpringBoot)