码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot 配置 Thymeleaf模板引擎

时间:2019-08-21 23:20:41      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:enc   ret   start   pid   map   etl   生成   dep   模板   

Thymeleaf模板引擎

什么是模板引擎

模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。


学习视频: http://www.itlaoqi.com/chapter/1688.html

源码地址: QQ群 814077650 , 群共享中自助下载

老齐的官网: itlaoqi.com (更多干货就在其中)


Thymeleaf的特点

  • Thymeleaf优点
    主流唯一的前后端通用模板引擎,静态html嵌入标签属性,浏览器可以直接打开模板文件,便于前后端联调。
    springboot官方推荐方案。
  • Thymeleaf缺点
    模板必须符合xml规范。
    慢!

    老齐的建议

  • 虽然Thymeleaf是Spring Boot官方默认,但在中国太过小众。
  • 对于Thymeleaf,重点掌握模板引擎的理念,语法了解就行。
  • 找工作重点学习Freemarker,前瞻学习Beetl。
  • JSP忘了它吧,在”去J2EE”的大趋势下,谁用谁傻X。

    Thymeleaf环境搭建

    pom引入thymeleaf依赖

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

application.properties增加thymeleaf配置

不使用缓存,保证修改源文件后及时刷新

spring.thymeleaf.cache=false

在templates中创建标准index.html文件

thymeleaf模板必须定义th命名空间,其他均为标准HTML标签

<!DOCTYPE html>
<!--最重要的是要引入thymeleaf的命名空间 -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    ...

在Controller准备测试数据,完成视图与模型绑定

@Controller
public class ThymeleafController {
    @RequestMapping("/")
    public ModelAndView index(String keyword) {
        //参数值index就对应了templates/index.html
        ModelAndView mav = new ModelAndView("index");
        ...
        //将查询结果放入mav
        mav.addObject("emps" , list);
        return mav;
    }
}

index.html使用th:each属性迭代emps集合

<tr th:each="emp,stat:${emps}" >
    <td>[[${emp.job}]]</td>
    <td>[[${#dates.format(emp.hiredate , 'yyyy年MM月dd日')}]]</td>
</tr>

SpringBoot 配置 Thymeleaf模板引擎

标签:enc   ret   start   pid   map   etl   生成   dep   模板   

原文地址:https://www.cnblogs.com/itlaoqi/p/11391751.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!