美文网首页
thymeleaf(一) ___ helloword

thymeleaf(一) ___ helloword

作者: 蜗牛船长 | 来源:发表于2018-06-03 02:40 被阅读0次
    thymeleaf是什么

    我们引用官网的一句介绍:
    thymeleaf是⾯向Web和独⽴环境的现代服务器端Java模板引擎,能够处 理HTML,XML,JavaScript,CSS甚⾄纯⽂本。Thymeleaf旨在提供⼀个优雅的、⾼度可维护的创建模板的⽅式。为了实 现这⼀⽬标,Thymeleaf建⽴在⾃然模板的概念上,将其逻辑注⼊到模板 ⽂件中,不会影响模板设计原型。 这改善了设计的沟通,弥合了设计和 开发团队之间的差距。

    简而言之就是一个类似freemarker一样的模板引擎,把我们后端的数据渲染到前端页面.thymeleaf的模板
    模板完美的遵循html规范,即使直接打开文件也可以显示出来,不会改变前端或美工设计的html页面,同时是springboot官方推荐的模板引擎.

    怎么使用

    使用一个简单的springboot demo来演示基本的使用

    • 1,项目引入thymeleaf的jar包.
      我这里的spring版本是2.0.2.RELEASE thymeleaf版本是3.0.9.RELEASE
    <dependency>
              <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
    
    • 2,application.yml配置文件中添加thymeleaf的配置
      spring:
        thymeleaf:
          servlet:
             content-type: text/html
          cache: false
          prefix: classpath:/templates/
          suffix: .html
          mode: HTML5
          encoding: UTF-8
    
    • 3,添加controller类
    @Controller
    public class IndexController {
    
    
       @GetMapping("/index")
       public String index(){
    
         return "index/index";
       }
     }
    
    
    • 4,创建一个html文件
      因为配置文件配置的prefix 是classpath:/templates/所以去templates 目录下创建一个目录
      index,index目录下创建一个普通html文件index.html


      image.png

    不过一个普通的html文件怎么就能被模板解析呢,索引需要在html顶部加入声明

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>测试</title>
    </head>
    <body>
    <p th:text="${hello}"></p>
    </body>
    </html>
    
    • 5,运行测试
      浏览器结果


      image.png

    相关文章

      网友评论

          本文标题:thymeleaf(一) ___ helloword

          本文链接:https://www.haomeiwen.com/subject/dcbrsftx.html