Thymeleaf字串轉義

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

  • 學習如何在Thymeleaf範本中顯示轉義值。
  • 已將HTML代碼片段設置為上下文模型,並將其作為變數名為html的字串。在第一個div中顯示HTML轉義字串,在第二個div中顯示未轉義字串。

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

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

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

package com.zaixian.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.zaixian.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>

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


上一篇: Thymeleaf字串連接 下一篇: Thymeleaf迭代列表