Spring Boot学习之旅:(十二)模版引擎-Thymeleaf

来源:互联网 发布:唯品会真假知乎 编辑:程序博客网 时间:2024/06/14 10:01

Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用。

Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。Thymeleaf的可扩展性也非常棒。你可以使用它定义自己的模板属性集合,这样就可以计算自定义表达式并使用自定义逻辑。这意味着Thymeleaf还可以作为模板引擎框架。
引入依赖
maven中直接引入

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

配置视图解析器

spring-boot很多配置都有默认配置,比如默认页面映射路径为classpath:/templates/*.html同样静态文件路径为classpath:/static/在application.properties中可以配置thymeleaf模板解析器属性.就像使用springMVC的JSP解析器配置一样

上述是默认路径如果是默认路径可以不写

添加配置

#thymeleaf startspring.thymeleaf.mode=HTML5spring.thymeleaf.encoding=UTF-8spring.thymeleaf.content-type=text/html#开发时关闭缓存,不然没法看到实时页面spring.thymeleaf.cache=false#thymeleaf end

controller

    @GetMapping()     public String hello(Model model) {        model.addAttribute("name", "cxhc");        return "index";    }

页面

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"        xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">      <head>          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />         <title>Hello World!</title>      </head>     大家好我是 <span th:text="${name}"></span></html> 

启动工程输入
http://localhost:8080/user
这里写图片描述

更多详细信息请看官网 解释更加详细和权威
http://www.thymeleaf.org/

文章地址:http://www.haha174.top/article/details/252777
源码地址:https://github.com/haha174/boot.git

阅读全文
0 0