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 的差別:兩者範本語法完全相同,但 text/template 不做任何跳脫。只要輸出是 HTML 網頁,一律改用 html/template,否則使用者輸入的 <script> 會原封不動輸出,造成 XSS 漏洞。

匯入


  1. import "text/template"

常用 API


New、Parse 與 Execute


基本流程分三步:template.New 建立一個有名字的範本,Parse 解析範本文字,Execute 把資料套進去並寫到 io.Writer(例如 os.Stdout、檔案、strings.Builder)。
template.Must 包住「回傳範本與錯誤」的呼叫,錯誤不為 nil 時 panic。範本通常寫死在程式裡,用 Must 讓寫錯的範本在啟動時就失敗。
注意:只有匯出(大寫開頭)的結構體欄位能在範本中存取,存取未匯出欄位會在 Execute 時回傳錯誤。
簽名:
  1. func New(name string) *Template
  2. func (t *Template) Parse(text string) (*Template, error)
  3. func (t *Template) Execute(wr io.Writer, data any) error
  4. func Must(t *Template, err error) *Template

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "text/template"
  6. )
  7. type User struct {
  8. Name string
  9. Email string
  10. Age int
  11. }
  12. func main() {
  13. tmpl := template.Must(template.New("card").Parse("Name: {{.Name}}\nEmail: {{.Email}}\nAge: {{.Age}}\n"))
  14. u := User{Name: "Gopher", Email: "gopher@example.com", Age: 15}
  15. if err := tmpl.Execute(os.Stdout, u); err != nil {
  16. fmt.Println(err)
  17. }
  18. m := map[string]string{"Name": "Map User", "Email": "map@example.com"}
  19. if err := tmpl.Execute(os.Stdout, m); err != nil {
  20. fmt.Println(err)
  21. }
  22. }

輸出:
  1. Name: Gopher
  2. Email: gopher@example.com
  3. Age: 15
  4. Name: Map User
  5. Email: map@example.com
  6. Age: <no value>

資料是映射時,不存在的鍵會輸出 <no value>;這個行為可以用 Option 調整(見下方)。

if、range 與 with


範本內的流程控制。if 判斷值是否為「真」:false、0、nil、空字串、長度為 0 的切片或映射都算假。range 走訪集合,區塊內的 dot 變成目前元素;可以寫 {{range $i, $v := .Items}} 同時取得索引。range 也能接 {{else}},集合為空時執行。
動作兩側加上 -(如 {{- 與 -}})會刪除該側相鄰的空白與換行,用來控制輸出排版。
簽名(範本語法):
  1. {{if pipeline}} T1 {{else if pipeline}} T2 {{else}} T3 {{end}}
  2. {{range pipeline}} T1 {{else}} T0 {{end}}
  3. {{with pipeline}} T1 {{end}}

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "text/template"
  6. )
  7. type Order struct {
  8. ID int
  9. Items []string
  10. Note string
  11. Shipped bool
  12. }
  13. const tmplText = `Order #{{.ID}}
  14. {{- range $i, $item := .Items}}
  15. {{$i}}. {{$item}}
  16. {{- else}}
  17. (no items)
  18. {{- end}}
  19. {{if .Shipped}}Status: shipped{{else}}Status: pending{{end}}
  20. {{with .Note}}Note: {{.}}{{else}}No note{{end}}
  21. `
  22. func main() {
  23. t := template.Must(template.New("order").Parse(tmplText))
  24. orders := []Order{
  25. {ID: 1, Items: []string{"book", "pen"}, Shipped: true, Note: "gift wrap"},
  26. {ID: 2},
  27. }
  28. for _, o := range orders {
  29. if err := t.Execute(os.Stdout, o); err != nil {
  30. fmt.Println(err)
  31. }
  32. }
  33. }

輸出:
  1. Order #1
  2. 0. book
  3. 1. pen
  4. Status: shipped
  5. Note: gift wrap
  6. Order #2
  7. (no items)
  8. Status: pending
  9. 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 之前呼叫,否則解析時會因為找不到函式而失敗。
簽名:
  1. type FuncMap map[string]any
  2. func (t *Template) Funcs(funcMap FuncMap) *Template

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. "text/template"
  7. )
  8. func main() {
  9. funcs := template.FuncMap{
  10. "upper": strings.ToUpper,
  11. "add": func(a, b int) int { return a + b },
  12. }
  13. const text = `{{range $i, $name := .}}{{add $i 1}}. {{upper $name}} ({{len $name}} chars){{"\n"}}{{end}}{{printf "total: %d" (len .)}}
  14. {{if gt (len .) 2}}many{{else}}few{{end}}
  15. `
  16. t := template.Must(template.New("list").Funcs(funcs).Parse(text))
  17. if err := t.Execute(os.Stdout, []string{"alice", "bob", "carol"}); err != nil {
  18. fmt.Println(err)
  19. }
  20. }

輸出:
  1. 1. ALICE (5 chars)
  2. 2. BOB (3 chars)
  3. 3. CAROL (5 chars)
  4. total: 3
  5. many

define、template 與 ExecuteTemplate


一份範本可以包含多個具名子範本:用 {{define "name"}}...{{end}} 定義,用 {{template "name" .}} 呼叫並傳入資料。ExecuteTemplate 直接執行指定名稱的子範本,常用於「共用版型 + 多個頁面」的結構。
注意:ExecuteTemplate 指定的名稱不存在時回傳錯誤。
簽名:
  1. func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error
  2. func (t *Template) Lookup(name string) *Template

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "text/template"
  6. )
  7. const text = `
  8. {{define "header"}}=== {{.}} ==={{end}}
  9. {{define "report"}}{{template "header" .Title}}
  10. {{range .Rows}}- {{.}}
  11. {{end}}{{end}}
  12. `
  13. func main() {
  14. t := template.Must(template.New("root").Parse(text))
  15. data := map[string]any{
  16. "Title": "Weekly Report",
  17. "Rows": []string{"fix bug #12", "release v1.2"},
  18. }
  19. if err := t.ExecuteTemplate(os.Stdout, "report", data); err != nil {
  20. fmt.Println(err)
  21. }
  22. fmt.Println(t.Lookup("header") != nil)
  23. err := t.ExecuteTemplate(os.Stdout, "missing", data)
  24. fmt.Println(err)
  25. }

輸出:
  1. === Weekly Report ===
  2. - fix bug #12
  3. - release v1.2
  4. true
  5. template: no template "missing" associated with template "root"

ParseFS 與 ParseFiles


範本內容多時通常放在獨立檔案。ParseFiles 從檔案路徑讀取;ParseFS 從任何 fs.FS 讀取,搭配 embed 可以把範本檔編進執行檔。每個檔案以「檔名(不含目錄)」作為範本名稱。
範例以 os.MkdirTemp 建立暫存目錄,用 os.DirFS 當作 fs.FS。
注意:模式沒有符合任何檔案時回傳錯誤。
簽名:
  1. func ParseFiles(filenames ...string) (*Template, error)
  2. func ParseFS(fsys fs.FS, patterns ...string) (*Template, error)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "text/template"
  7. )
  8. func main() {
  9. dir, err := os.MkdirTemp("", "tmpl")
  10. if err != nil {
  11. fmt.Println(err)
  12. return
  13. }
  14. defer os.RemoveAll(dir)
  15. files := map[string]string{
  16. "hello.tmpl": "Hello, {{.}}!\n",
  17. "bye.tmpl": "Bye, {{.}}.\n",
  18. }
  19. for name, body := range files {
  20. if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
  21. fmt.Println(err)
  22. return
  23. }
  24. }
  25. t, err := template.ParseFS(os.DirFS(dir), "*.tmpl")
  26. if err != nil {
  27. fmt.Println(err)
  28. return
  29. }
  30. t.ExecuteTemplate(os.Stdout, "hello.tmpl", "Gopher")
  31. t.ExecuteTemplate(os.Stdout, "bye.tmpl", "Gopher")
  32. _, err = template.ParseFS(os.DirFS(dir), "*.html")
  33. fmt.Println(err)
  34. }

輸出:
  1. Hello, Gopher!
  2. Bye, Gopher.
  3. template: pattern matches no files: `*.html`

Option


調整範本執行時的行為。最常用的是 missingkey,決定映射中找不到鍵時怎麼辦:
設定行為
missingkey=default(預設)輸出 <no value>
missingkey=zero輸出該型別的零值
missingkey=errorExecute 立即回傳錯誤

產生設定檔這類「少一個值就是錯」的情境,建議用 missingkey=error,及早發現資料缺漏。
簽名:
  1. func (t *Template) Option(opt ...string) *Template

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "text/template"
  6. )
  7. func main() {
  8. data := map[string]string{"host": "localhost"}
  9. text := "host={{.host}} port={{.port}}\n"
  10. for _, opt := range []string{"missingkey=default", "missingkey=zero", "missingkey=error"} {
  11. t := template.Must(template.New("cfg").Option(opt).Parse(text))
  12. fmt.Print(opt, ": ")
  13. if err := t.Execute(os.Stdout, data); err != nil {
  14. fmt.Println()
  15. fmt.Println("error:", err)
  16. }
  17. }
  18. }

輸出:
  1. missingkey=default: host=localhost port=<no value>
  2. missingkey=zero: host=localhost port=
  3. missingkey=error: host=localhost port=
  4. 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,text/template 不做任何跳脫

資料來源