Thymeleaf字串跳脫


本文章將介紹Thymeleaf標準表示式語法中的概念。

  • 學習如何在Thymeleaf模板中顯示跳脫值。
  • 已將HTML程式碼片段設定為上下文模型,並將其作為變數名為html的字串。在第一個div中顯示HTML跳脫字串,在第二個div中顯示未跳脫字串。

如果要上機實踐,請參考:Thymeleaf+SpringMVC5範例專案。這裡不再重複建立專案的過程,這裡將只介紹如何使用Thymeleaf標準表示式和標籤。

這裡建立一個Maven Web專案: thymeleaf-tutorials ,其目錄結構如下所示 -

控制器類的實現:MyController.java -

package com.yiibai.spring.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.yiibai.spring.bean.Product;

@Controller
public class MyController {

   @GetMapping("/")
   public String index(Model model) throws ParseException {
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      Product product = new Product("花生油", 129, sdf.parse("2018-02-18"));
      model.addAttribute("product", product);
      return "index";
   }

   @GetMapping("/escape")
   public String escape(Model model) throws ParseException {
     String html =  "Welcome to our <b>fantastic</b> grocery store!";
      model.addAttribute("html", html);
      return "escape";
   }
}

模板檔案的實現:/webapp/WEB-INFO/views/escape.html -

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/css/main.css}" />
<title>SpringMVC5+Thymeleaf範例</title>
</head>
<body>
    <h2>Spring MVC5 + Thymeleaf 字串跳脫範例</h2>
    <div th:text="${html}">Some escaped text</div>
    <div th:utext="${html}">Some unescaped text</div>
</body>
</html>

執行上面專案,在瀏覽器中顯示效果如下 -