# html/template

`html/template` 用來產生 HTML：範本語法和 `text/template` 相同，但會依照插入位置自動跳脫資料，防止 XSS 攻擊。

## 這個套件做什麼

網頁常把使用者輸入的內容（留言、暱稱、搜尋字）放進 HTML。如果有人把暱稱設成 `<script>alert(1)</script>`，直接輸出就會在其他人的瀏覽器執行這段程式，這種攻擊叫跨站腳本攻擊（XSS，Cross-Site Scripting）。

`html/template` 的做法是「情境感知跳脫」（contextual autoescaping）：它在解析範本時理解 HTML 結構，知道每個 `{{ }}` 落在一般文字、屬性值、URL、JavaScript 或 CSS 裡，再對資料套用該位置正確的跳脫方式。你不用手動呼叫跳脫函式，預設就是安全的。

和 [`text/template`](/pkg-text-template) 的關係：

| | `text/template` | `html/template` |
| --- | --- | --- |
| 範本語法 | 相同 | 相同 |
| 自動跳脫 | 無 | 依 HTML 情境跳脫 |
| 適用輸出 | 設定檔、程式碼、純文字 | HTML 網頁、HTML Email |

範本語法（`{{.Field}}`、`if`、`range`、`define`、`FuncMap`）的詳細說明見 [text/template](/pkg-text-template)，本頁專注在 HTML 特有的行為。

## 匯入

```go
import "html/template"
```

同一個檔案不要同時匯入兩個 template 套件；如果真的需要，替其中一個取別名。

## 常用 API

### New、Parse 與 Execute（自動跳脫）

用法和 `text/template` 一樣。差別在輸出：資料中的 `<`、`>`、`&`、`"`、`'` 會被轉成 HTML 實體（entity），例如 `<` 變成 `&lt;`，瀏覽器只會把它顯示成文字，不會當成標籤。

簽名：

```go
func New(name string) *Template
func (t *Template) Parse(text string) (*Template, error)
func (t *Template) Execute(wr io.Writer, data any) error
func Must(t *Template, err error) *Template
```

範例：

```go
package main

import (
	"fmt"
	"html/template"
	"os"
)

type Comment struct {
	Author string
	Body   string
}

func main() {
	t := template.Must(template.New("c").Parse(`<div class="comment"><b>{{.Author}}</b>: {{.Body}}</div>
`))

	c := Comment{
		Author: "Mallory",
		Body:   `<script>alert("hi")</script> & bye`,
	}
	if err := t.Execute(os.Stdout, c); err != nil {
		fmt.Println(err)
	}
}
```

輸出：

```text
<div class="comment"><b>Mallory</b>: &lt;script&gt;alert(&#34;hi&#34;)&lt;/script&gt; &amp; bye</div>
```

### 情境感知跳脫

同一份資料放在不同位置，跳脫方式也不同：

- HTML 文字中：轉成 HTML 實體
- 屬性值中：轉成 HTML 實體，連引號也會處理
- `href`、`src` 這類 URL 屬性：先檢查網址協定，`javascript:` 這類危險網址會被換成 `#ZgotmplZ`，再做 URL 編碼
- `<script>` 中：轉成 JavaScript 值（字串會加上引號並跳脫）

`#ZgotmplZ` 是一個刻意的記號，看到它代表「有不安全的值被擋下來了」。

範例：

```go
package main

import (
	"fmt"
	"html/template"
	"os"
)

func main() {
	const page = `<a href="/search?q={{.Query}}" title="{{.Query}}">{{.Query}}</a>
<a href="{{.Link}}">link</a>
<script>var q = {{.Query}};</script>
`
	t := template.Must(template.New("p").Parse(page))

	data := map[string]string{
		"Query": `go & "rust"`,
		"Link":  "javascript:alert(1)",
	}
	if err := t.Execute(os.Stdout, data); err != nil {
		fmt.Println(err)
	}
}
```

輸出：

```text
<a href="/search?q=go%20%26%20%22rust%22" title="go &amp; &#34;rust&#34;">go &amp; &#34;rust&#34;</a>
<a href="#ZgotmplZ">link</a>
<script>var q = "go \u0026 \"rust\"";</script>
```

### template.HTML 等信任型別

有時資料本身就是可信任的 HTML，例如由程式產生、已經清理過的 Markdown 轉換結果，不希望被跳脫。這時把字串轉成 `template.HTML`，範本會原樣輸出。同類的型別還有 `template.URL`、`template.JS`、`template.CSS`、`template.HTMLAttr`。

注意：這些型別等於告訴套件「我保證這段內容安全」，跳過了所有保護。絕對不要把使用者輸入直接轉成 `template.HTML`，否則等於自己打開 XSS 漏洞。

簽名：

```go
type HTML string
type URL string
type JS string
```

範例：

```go
package main

import (
	"fmt"
	"html/template"
	"os"
)

func main() {
	t := template.Must(template.New("t").Parse(`plain: {{.Plain}}
trusted: {{.Trusted}}
<a href="{{.Link}}">tel</a>
`))

	data := map[string]any{
		"Plain":   "<em>hello</em>",
		"Trusted": template.HTML("<em>hello</em>"),
		"Link":    template.URL("tel:+886-2-1234-5678"),
	}
	if err := t.Execute(os.Stdout, data); err != nil {
		fmt.Println(err)
	}
}
```

輸出：

```text
plain: &lt;em&gt;hello&lt;/em&gt;
trusted: <em>hello</em>
<a href="tel:&#43;886-2-1234-5678">tel</a>
```

`tel:` 不在預設允許的協定（`http`、`https`、`mailto`）中，若沒有轉成 `template.URL` 會被換成 `#ZgotmplZ`。

### define 與 ExecuteTemplate（版型組合）

網站常見「共用版型 + 各頁內容」的結構。在版型裡用 `{{block "name" .}}預設內容{{end}}` 留一個可被替換的區塊，各頁用 `{{define "name"}}` 提供自己的內容。`Clone` 複製一份已解析的範本，讓不同頁面各自覆寫區塊而不互相影響。

注意：`html/template` 的範本第一次執行後就不能再 `Parse` 新內容（會回傳錯誤），所以要在執行前 `Clone` 出各頁的範本。

簽名：

```go
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error
func (t *Template) Clone() (*Template, error)
```

範例：

```go
package main

import (
	"fmt"
	"html/template"
	"os"
)

const layout = `<html><title>{{block "title" .}}My Site{{end}}</title>
<body>{{block "content" .}}{{end}}</body></html>
`

func main() {
	base := template.Must(template.New("layout").Parse(layout))

	home := template.Must(template.Must(base.Clone()).Parse(
		`{{define "content"}}<h1>Welcome, {{.}}</h1>{{end}}`))
	about := template.Must(template.Must(base.Clone()).Parse(
		`{{define "title"}}About{{end}}{{define "content"}}<p>About {{.}}</p>{{end}}`))

	if err := home.ExecuteTemplate(os.Stdout, "layout", "<Gopher>"); err != nil {
		fmt.Println(err)
	}
	if err := about.ExecuteTemplate(os.Stdout, "layout", "Go"); err != nil {
		fmt.Println(err)
	}
}
```

輸出：

```text
<html><title>My Site</title>
<body><h1>Welcome, &lt;Gopher&gt;</h1></body></html>
<html><title>About</title>
<body><p>About Go</p></body></html>
```

### 搭配 net/http 輸出網頁

實務上 `html/template` 最常和 [`net/http`](/pkg-net-http) 一起用：處理函式把 `http.ResponseWriter` 當成 `io.Writer` 傳給 `Execute`。範本在程式啟動時解析一次，每個請求只執行。

範例用 [`httptest`](/pkg-net-http-httptest) 在本機起一個伺服器，不需要連外網。

範例：

```go
package main

import (
	"fmt"
	"html/template"
	"io"
	"net/http"
	"net/http/httptest"
)

var page = template.Must(template.New("hello").Parse(
	`<p>Hello, {{.}}!</p>`))

func handler(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("name")
	if name == "" {
		name = "guest"
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := page.Execute(w, name); err != nil {
		http.Error(w, "render failed", http.StatusInternalServerError)
	}
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(handler))
	defer srv.Close()

	for _, q := range []string{"", "?name=Gopher", "?name=%3Cb%3Ex%3C/b%3E"} {
		resp, err := http.Get(srv.URL + q)
		if err != nil {
			fmt.Println(err)
			return
		}
		body, _ := io.ReadAll(resp.Body)
		resp.Body.Close()
		fmt.Println(string(body))
	}
}
```

輸出：

```text
<p>Hello, guest!</p>
<p>Hello, Gopher!</p>
<p>Hello, &lt;b&gt;x&lt;/b&gt;!</p>
```

### HTMLEscapeString

不透過範本、單純把一段字串跳脫成安全的 HTML 文字。適合少量手動組字串的場合；大量 HTML 輸出仍建議用範本。

簽名：

```go
func HTMLEscapeString(s string) string
```

範例：

```go
package main

import (
	"fmt"
	"html/template"
)

func main() {
	fmt.Println(template.HTMLEscapeString(`<a href="x">Tom & Jerry's</a>`))
}
```

輸出：

```text
&lt;a href=&#34;x&#34;&gt;Tom &amp; Jerry&#39;s&lt;/a&gt;
```

## 重點整理

- 輸出 HTML 一律用 `html/template`；語法與 `text/template` 相同
- 套件依資料所在位置（文字、屬性、URL、script）自動選擇跳脫方式
- 看到 `#ZgotmplZ` 代表有不安全的值被擋下
- `template.HTML`、`template.URL` 會跳過跳脫，只能用在你能保證安全的內容
- 範本在啟動時解析一次；需要多頁版型時先 `Clone` 再覆寫區塊

## 資料來源

- [dsxwk/go-docs（標準庫分類架構參考）](https://github.com/dsxwk/go-docs)
- [pkg.go.dev：html/template](https://pkg.go.dev/html/template)
- [Go 1.26.0 原始碼：src/html/template](https://github.com/golang/go/tree/go1.26.0/src/html/template)
