spring Boot 2.x | 模板引擎 thymeleaf

栏目: Java · 发布时间: 5年前

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

thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用,比如 <span th:text="${name}">你好</span> 这个标签,当直接打开静态页面的时候会显示你好,当使用动态数据之后会显示动态的数据,将 你好 覆盖

引入依赖

在springboot中使用thymeleaf,项目依赖web模块和thymeleaf

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

配置文件

springboot提供了 Thymeleaf 的默认配置,如果想要更改默认配置,需要在配置文件中修改相关属性

spring:
  thymeleaf:
    mode: HTML5
    servlet:
      content-type: text/html
    cache: false #是否开启缓存
    encoding: UTF-8 #编码
    prefix: classpath:/templates/ #模板路径
    suffix: .html # 后缀

模板

Spring Boot 官方推荐使用 Thymeleaf 模板引擎,默认的模板路径在src/main/resources/templates

新建一个test.html模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
</head>
<body>
<h4><span th:text="${name}">你好</span></h4>
我的博客地址是<span th:text="${url}"></span>
</body>
</html>

写个controller测试下

/**
 * @author: chenmingyu
 * @date: 2019/2/27 11:04
 * @description:
 */
@Controller
public class TestController {

    @GetMapping("test")
    public String test(Model model){

        model.addAttribute("name","叫我明羽");
        model.addAttribute("url","https://chenmingyu.top");
        return "test";
    }
}

访问 http://localhost:8080/test

spring Boot 2.x | 模板引擎 thymeleaf

spring:
  thymeleaf:
    mode: HTML5
    servlet:
      content-type: text/html
    cache: false #是否开启缓存
    encoding: UTF-8 #编码
    prefix: classpath:/templates/ #模板路径
    suffix: .html # 后缀

想了解更多关于Thymeleaf的更多标签,语法可以访问 Thymeleaf官网


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

算法小时代

算法小时代

Serge Abiteboul、Gilles Dowek / 任铁 / 人民邮电出版社 / 2017-10-1 / 39.00元

算法与人工智能是当下最热门的话题之一,技术大发展的同时也引发了令人忧心的技术和社会问题。本书生动介绍了算法的数学原理和性质,描述了算法单纯、本质的功能,分析了算法和人工智能对人类社会现状及未来发展的影响力及其成因。一起来看看 《算法小时代》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具