spring Boot 2.x | 模板引擎 thymeleaf

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

内容简介: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官网


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

查看所有标签

猜你喜欢:

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

TCP/IP详解 卷1:协议

TCP/IP详解 卷1:协议

W.Richard Stevens / 范建华 / 机械工业出版社 / 2000-4-1 / 45.00元

《TCP/IP详解卷1:协议》是一本完整而详细的TCP/IP协议指南。描述了属于每一层的各个协议以及它们如何在不同操作系统中运行。作者W.Richard Stevens用Lawrence Berkeley实验室的tcpdump程序来捕获不同操作系统和TCP/IP实现之间传输的不同分组。对tcpdump输出的研究可以帮助理解不同协议如何工作。 《TCP/IP详解卷1:协议》适合作为计算机专业学......一起来看看 《TCP/IP详解 卷1:协议》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具