# text/template

`text/template` 是 Go 內建的文字範本引擎：寫好一份含有佔位符號的範本，再把資料填進去產生最終文字。

## 這個套件做什麼

範本（template）像是「填空題」：`Hello, {{.Name}}!` 裡的 `{{.Name}}` 是空格，執行時用資料把它填滿。適合產生設定檔、程式碼、Email 內容、命令列報表這類「格式固定、內容會變」的文字。

範本裡 `{{ }}` 包起來的部分叫「動作」（action），其餘文字原樣輸出。常見動作：

| 動作 | 意思 |
| --- | --- |
| `{{.}}` | 目前的資料本身（稱為 dot） |
| `{{.Name}}` | 資料的欄位、方法或映射鍵 |
| `{{if .X}}...{{else}}...{{end}}` | 條件判斷 |
| `{{range .Items}}...{{end}}` | 走訪切片、映射、channel 或整數 |
| `{{with .X}}...{{end}}` | X 非零值時，把 dot 換成 X |
| `{{len .Items}}` | 呼叫函式 |
| `{{.Name \| printf "%q"}}` | 管線（pipeline），把前面的結果當最後一個參數傳給後面 |
| `{{/* 註解 */}}` | 範本註解，不會輸出 |

和 [`html/template`](/pkg-html-template) 的差別：兩者範本語法完全相同，但 `text/template` 不做任何跳脫。只要輸出是 HTML 網頁，一律改用 `html/template`，否則使用者輸入的 `<script>` 會原封不動輸出，造成 XSS 漏洞。

## 匯入

```go
import "text/template"
```

## 常用 API

### New、Parse 與 Execute

基本流程分三步：`template.New` 建立一個有名字的範本，`Parse` 解析範本文字，`Execute` 把資料套進去並寫到 `io.Writer`（例如 `os.Stdout`、檔案、`strings.Builder`）。

`template.Must` 包住「回傳範本與錯誤」的呼叫，錯誤不為 nil 時 panic。範本通常寫死在程式裡，用 `Must` 讓寫錯的範本在啟動時就失敗。

注意：只有匯出（大寫開頭）的結構體欄位能在範本中存取，存取未匯出欄位會在 `Execute` 時回傳錯誤。

簽名：

```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"
	"os"
	"text/template"
)

type User struct {
	Name  string
	Email string
	Age   int
}

func main() {
	tmpl := template.Must(template.New("card").Parse("Name: {{.Name}}\nEmail: {{.Email}}\nAge: {{.Age}}\n"))

	u := User{Name: "Gopher", Email: "gopher@example.com", Age: 15}
	if err := tmpl.Execute(os.Stdout, u); err != nil {
		fmt.Println(err)
	}

	m := map[string]string{"Name": "Map User", "Email": "map@example.com"}
	if err := tmpl.Execute(os.Stdout, m); err != nil {
		fmt.Println(err)
	}
}
```

輸出：

```text
Name: Gopher
Email: gopher@example.com
Age: 15
Name: Map User
Email: map@example.com
Age: <no value>
```

資料是映射時，不存在的鍵會輸出 `<no value>`；這個行為可以用 `Option` 調整（見下方）。

### if、range 與 with

範本內的流程控制。`if` 判斷值是否為「真」：`false`、0、nil、空字串、長度為 0 的切片或映射都算假。`range` 走訪集合，區塊內的 dot 變成目前元素；可以寫 `{{range $i, $v := .Items}}` 同時取得索引。`range` 也能接 `{{else}}`，集合為空時執行。

動作兩側加上 `-`（如 `{{- ` 與 ` -}}`）會刪除該側相鄰的空白與換行，用來控制輸出排版。

簽名（範本語法）：

```text
{{if pipeline}} T1 {{else if pipeline}} T2 {{else}} T3 {{end}}
{{range pipeline}} T1 {{else}} T0 {{end}}
{{with pipeline}} T1 {{end}}
```

範例：

```go
package main

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

type Order struct {
	ID      int
	Items   []string
	Note    string
	Shipped bool
}

const tmplText = `Order #{{.ID}}
{{- range $i, $item := .Items}}
  {{$i}}. {{$item}}
{{- else}}
  (no items)
{{- end}}
{{if .Shipped}}Status: shipped{{else}}Status: pending{{end}}
{{with .Note}}Note: {{.}}{{else}}No note{{end}}
`

func main() {
	t := template.Must(template.New("order").Parse(tmplText))

	orders := []Order{
		{ID: 1, Items: []string{"book", "pen"}, Shipped: true, Note: "gift wrap"},
		{ID: 2},
	}
	for _, o := range orders {
		if err := t.Execute(os.Stdout, o); err != nil {
			fmt.Println(err)
		}
	}
}
```

輸出：

```text
Order #1
  0. book
  1. pen
Status: shipped
Note: gift wrap
Order #2
  (no items)
Status: pending
No note
```

### Funcs 與 FuncMap

範本內建了一些函式：`len`、`index`、`printf`、`and`、`or`、`not`、`eq`、`ne`、`lt`、`le`、`gt`、`ge` 等。需要自己的函式時，把它放進 `template.FuncMap`（名稱對應函式的映射），再用 `Funcs` 註冊。

函式必須回傳一個值，或回傳「一個值加一個 error」；回傳的 error 不為 nil 時，`Execute` 會中止並回傳該錯誤。

注意：`Funcs` 必須在 `Parse` 之前呼叫，否則解析時會因為找不到函式而失敗。

簽名：

```go
type FuncMap map[string]any
func (t *Template) Funcs(funcMap FuncMap) *Template
```

範例：

```go
package main

import (
	"fmt"
	"os"
	"strings"
	"text/template"
)

func main() {
	funcs := template.FuncMap{
		"upper": strings.ToUpper,
		"add":   func(a, b int) int { return a + b },
	}

	const text = `{{range $i, $name := .}}{{add $i 1}}. {{upper $name}} ({{len $name}} chars){{"\n"}}{{end}}{{printf "total: %d" (len .)}}
{{if gt (len .) 2}}many{{else}}few{{end}}
`
	t := template.Must(template.New("list").Funcs(funcs).Parse(text))
	if err := t.Execute(os.Stdout, []string{"alice", "bob", "carol"}); err != nil {
		fmt.Println(err)
	}
}
```

輸出：

```text
1. ALICE (5 chars)
2. BOB (3 chars)
3. CAROL (5 chars)
total: 3
many
```

### define、template 與 ExecuteTemplate

一份範本可以包含多個具名子範本：用 `{{define "name"}}...{{end}}` 定義，用 `{{template "name" .}}` 呼叫並傳入資料。`ExecuteTemplate` 直接執行指定名稱的子範本，常用於「共用版型 + 多個頁面」的結構。

注意：`ExecuteTemplate` 指定的名稱不存在時回傳錯誤。

簽名：

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

範例：

```go
package main

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

const text = `
{{define "header"}}=== {{.}} ==={{end}}
{{define "report"}}{{template "header" .Title}}
{{range .Rows}}- {{.}}
{{end}}{{end}}
`

func main() {
	t := template.Must(template.New("root").Parse(text))

	data := map[string]any{
		"Title": "Weekly Report",
		"Rows":  []string{"fix bug #12", "release v1.2"},
	}
	if err := t.ExecuteTemplate(os.Stdout, "report", data); err != nil {
		fmt.Println(err)
	}

	fmt.Println(t.Lookup("header") != nil)
	err := t.ExecuteTemplate(os.Stdout, "missing", data)
	fmt.Println(err)
}
```

輸出：

```text
=== Weekly Report ===
- fix bug #12
- release v1.2
true
template: no template "missing" associated with template "root"
```

### ParseFS 與 ParseFiles

範本內容多時通常放在獨立檔案。`ParseFiles` 從檔案路徑讀取；`ParseFS` 從任何 `fs.FS` 讀取，搭配 [`embed`](/embed-files) 可以把範本檔編進執行檔。每個檔案以「檔名（不含目錄）」作為範本名稱。

範例以 `os.MkdirTemp` 建立暫存目錄，用 `os.DirFS` 當作 `fs.FS`。

注意：模式沒有符合任何檔案時回傳錯誤。

簽名：

```go
func ParseFiles(filenames ...string) (*Template, error)
func ParseFS(fsys fs.FS, patterns ...string) (*Template, error)
```

範例：

```go
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"text/template"
)

func main() {
	dir, err := os.MkdirTemp("", "tmpl")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)

	files := map[string]string{
		"hello.tmpl": "Hello, {{.}}!\n",
		"bye.tmpl":   "Bye, {{.}}.\n",
	}
	for name, body := range files {
		if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
			fmt.Println(err)
			return
		}
	}

	t, err := template.ParseFS(os.DirFS(dir), "*.tmpl")
	if err != nil {
		fmt.Println(err)
		return
	}
	t.ExecuteTemplate(os.Stdout, "hello.tmpl", "Gopher")
	t.ExecuteTemplate(os.Stdout, "bye.tmpl", "Gopher")

	_, err = template.ParseFS(os.DirFS(dir), "*.html")
	fmt.Println(err)
}
```

輸出：

```text
Hello, Gopher!
Bye, Gopher.
template: pattern matches no files: `*.html`
```

### Option

調整範本執行時的行為。最常用的是 `missingkey`，決定映射中找不到鍵時怎麼辦：

| 設定 | 行為 |
| --- | --- |
| `missingkey=default`（預設） | 輸出 `<no value>` |
| `missingkey=zero` | 輸出該型別的零值 |
| `missingkey=error` | `Execute` 立即回傳錯誤 |

產生設定檔這類「少一個值就是錯」的情境，建議用 `missingkey=error`，及早發現資料缺漏。

簽名：

```go
func (t *Template) Option(opt ...string) *Template
```

範例：

```go
package main

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

func main() {
	data := map[string]string{"host": "localhost"}
	text := "host={{.host}} port={{.port}}\n"

	for _, opt := range []string{"missingkey=default", "missingkey=zero", "missingkey=error"} {
		t := template.Must(template.New("cfg").Option(opt).Parse(text))
		fmt.Print(opt, ": ")
		if err := t.Execute(os.Stdout, data); err != nil {
			fmt.Println()
			fmt.Println("error:", err)
		}
	}
}
```

輸出：

```text
missingkey=default: host=localhost port=<no value>
missingkey=zero: host=localhost port=
missingkey=error: host=localhost port=
error: template: cfg:1:22: executing "cfg" at <.port>: map has no entry for key "port"
```

## 重點整理

- 流程是 `New` → `Parse` → `Execute`，寫死的範本用 `template.Must` 包起來
- `{{.}}` 是目前資料，`{{.Field}}` 只能存取匯出欄位；`{{-` 與 `-}}` 修剪空白
- 自訂函式用 `FuncMap` 註冊，而且要在 `Parse` 之前呼叫 `Funcs`
- 多個子範本用 `define`／`template` 組合，用 `ExecuteTemplate` 指定執行哪一個
- `Option("missingkey=error")` 讓缺少的資料直接報錯
- 輸出 HTML 時改用 [`html/template`](/pkg-html-template)，`text/template` 不做任何跳脫

## 資料來源

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