Skip to content

text/template

  1. template.New()
  2. Funcs()(可选)
  3. Parse() / 解析 AST
  4. Execute()
go
package main

import (
	"os"
	"text/template"
)

func main() {
	tmpl := template.Must(template.New("test").Parse("Hello {{.}}"))
	tmpl.Execute(os.Stdout, "World")
}

. 表示当前作用域点数据

数据可以是基本类型,可以是 struct

go
type User struct {
	Name string
	Age  int
}
go
Name: {{.Name}}
Age: {{.Age}}

变量

go
{{$name := .Name}}
Hello {{$name}}

if

{{if .Admin}}
Admin user
{{else}}
Normal user
{{end}}

range

go
[]string{"a", "b", "c"}
go
tmpl := `
{{range .}}
- {{.}}
{{end}}
`

输出

- a
- b
- c

管道

go
{{.Name | printf "%s!!!"}}

意思是

printf("%s!!!", .Name)

自定义函数

go
package main

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

func main() {

	funcMap := template.FuncMap{
		"upper": strings.ToUpper,
	}

	tmpl := template.Must(
		template.New("test").Funcs(funcMap).Parse("{{upper .}}"),
	)

	tmpl.Execute(os.Stdout, "hello")
}

嵌套模板

go
{{define "header"}}
Header content
{{end}}

{{template "header"}}

template.Must

大概是这样:

go
func Must(t *Template, err error) *Template {
    if err != nil {
        panic(err)
    }
    return t
}