- 简单使用:
fmt.Printf("I am %s\n", name) // I am AlphaGo
- 导出
Name,使用struct:
t := template.Must(template.New("my").Parse("I am {{.Name}}\n"))
t.Execute(os.Stdout, struct{ Name string }{name}) // I am AlphaGo
- 小写
name,使用map:
t2 := template.Must(template.New("my").Parse("I am {{.name}}\n"))
t2.Execute(os.Stdout, map[string]string{"name": name}) // I am AlphaGo
- 使用
.:
t3 := template.Must(template.New("my").Parse("I am {{.}}\n"))
t3.Execute(os.Stdout, name) // I am AlphaGo
全部 - try it on The Go Playground:
package main
import (
"fmt"
"os"
"text/template"
)
func main() {
name := "AlphaGo"
fmt.Printf("I am %s\n", name)
t := template.Must(template.New("my").Parse("I am {{.Name}}\n"))
t.Execute(os.Stdout, struct{ Name string }{name}) // I am AlphaGo
t2 := template.Must(template.New("my").Parse("I am {{.name}}\n"))
t2.Execute(os.Stdout, map[string]string{"name": name}) // I am AlphaGo
t3 := template.Must(template.New("my").Parse("I am {{.}}\n"))
t3.Execute(os.Stdout, name) // I am AlphaGo
}