1. 程式人生 > >六、SpringBoot之模板引擎

六、SpringBoot之模板引擎

市面上的模版引擎:JSP、Velocity、Freemarker、Thymeleaf

SpringBoot推薦的Thymeleaf:語法更簡單,功能更強大;

1、引入Thymeleaf

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
切換thymeleaf版本
<properties>
   <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
   <!-- 佈局功能的支援程式  thymeleaf3主程式 適配 layout2以上版本 -->
   <!-- thymeleaf2 適配  layout1-->
   <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>

2、Thymeleaf使用

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    //只要我們把HTML頁面放在classpath:/templates/,thymeleaf就能自動渲染;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
    private boolean cache;
    private Integer templateResolverOrder;
    private String[] viewNames;
    private String[] excludedViewNames;
    private boolean enableSpringElCompiler;
    private boolean enabled;
    private final ThymeleafProperties.Servlet servlet;
    private final ThymeleafProperties.Reactive reactive;

使用步驟:

  • 1.java
    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("hello","<h1>你好</h1>");
        map.put("users",Arrays.asList("zhangsan","lisi","wangwu"));
        //會去找classpath:/templates/success.html
        return "success";
    }
  • 2.匯入thymeleaf的名稱空間
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  • 3.使用thymeleaf語法;
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>成功!</h1>
<!--th:text 將div裡面的文字內容設定為 -->
<div id="div01" name="myDiv" th:id="${hello}" th:name="${hello}" th:text="${hello}">這是顯示歡迎資訊</div>
<hr/>
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<hr/>

<!-- th:each每次遍歷都會生成當前這個標籤:3個h4-->
<h4 th:text="${user}" th:each="user:${users}"></h4>
<hr/>
<h4>
   <span th:each="user:${users}">[[${user}]]</span>
</h4>
</body>
</html>

3、Thymeleaf語法規則

  • 1.th:text;改變當前元素裡面的文字內容;

​ th:任意html屬性;來替換原生屬性的值

  • 2.表示式