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官网


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

查看所有标签

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

CSS3 Solutions

CSS3 Solutions

Marco Casario / Apress / 2012-8-13 / GBP 35.50

CSS3 brings a mass of changes, additions, and improvements to CSS across a range of new modules. Web designers and developers now have a whole host of new techniques up their sleeves, from working wit......一起来看看 《CSS3 Solutions》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具