• [Spring]Thymeleaf——XML/XHTML/HTML5模板引擎


    什么是Thymeleaf

    Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。

    Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
    官方文档


    使用

    Maven依赖

    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-thymeleafartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    application.yml配置

    • cache : 设置thymeleaf的缓存。默认true,用于测试。
    • encoding : 编码
    • prefix : classpath:/templates/,模板文件路径
    spring:
      thymeleaf:
        cache: false
        encoding: UTF-8
    
    • 1
    • 2
    • 3
    • 4

    创建html

    在resources/templates/目录中创建xxx.html。
    这里创建了hello.html。

    DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>titletitle>
    head>
    <body>
    	
    	<div th:text="${key}">div>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    Controller返回页面

    @Controller
    @RequestMapping("/test")
    public class TestController {
    
        /**
        * 访问test/hello,返回hello.html
        */
        @RequestMapping("/hello")
        public String hello(Model model){
            model.addAttribute("key","hello world");
            return "hello";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    常用标签

    标签作用
    th:id替换id
    th:text文本替换
    th:utext支持html的文本替换
    th:object替换对象
    th:value替换值
    th:each迭代
    th:href替换超链接
    th:src替换资源

    取值

    ${Key}

    循环
    <ul th:each="item:${MyList}">
        <li th:text="${item}">li>
    ul>
    
    • 1
    • 2
    • 3

    引入资源

    @{资源地址}

    读取配置文件中数据

    #{key}

    引用公共页面

    • th:insert:将代码块片段整个插入到使用了 th:insert 属性的 HTML 标签中;
    • th:replace:将代码块片段整个替换使用了 th:replace 属性的 HTML 标签中;
    • th:include:将代码块片段包含的内容插入到使用了 th:include 属性的 HTML 标签中。
  • 相关阅读:
    CUDA小白 - NPP(11) 图像处理 Comparison Operations
    v-charts
    解决EnableKeyword(“_Emission“)运行状态不起作用
    软设上午题错题知识点2
    【JavaWeb·3】Servlet+JDBC实现对数据库内数据增删改查
    JavaScript高级,ES6 笔记 第一天
    电脑怎么迁移游戏资源,数据迁移能把游戏数据迁移吗
    A. Short Sort
    vm2 组件存在沙箱逃逸漏洞
    软件测试之Web测试流程和方法
  • 原文地址:https://blog.csdn.net/malu_record/article/details/133819679