1. package main
  2. import "text/template"
  3. func main(){
  4. //
  5. // 解析模板 字符串
  6. text:="我的名字叫{{.}}" // {{.}} 叫占位符
  7. tpl,err:=template.New("test").Parse(text) //先new一个对象
  8. if err !=nil{
  9. fmt.Println(err)
  10. }
  11. tpl.Execute(os.Stdout,"kk") //根据tpl进行执行
  12. tpl.Execute(os.Stdout,1)
  13. tpl.Execute(os.Stdout,true)
  14. tpl.Execute(os.Stdout,[]int{1,2,3})
  15. tpl.Execute(os.Stdout,map[string]string{"1":"1"})
  16. text = "性别:{{ if . }} 男 {{ else }} 女 {{ end }}\n" //if 条件判断
  17. }
  18. tpl,_=template.New("test").Parse(text)
  19. tpl.Execute(os.Stdout,false)
  20. text = "性别:{{ if =. }} 男 {{ else }} 女 {{ end }}\n" // 这种条件判断的语法是不支持的,"=" 可是使用 “eq”表示
  21. // gt >, lt < , gte >=, lte <=, eq=, neq!=
  22. text = "性别:{{ if eq 1 . }} 男 {{ else }} 女 {{ end }}\n" //if 条件判断
  23. tpl,_=template.New("test").Parse(text)
  24. tpl.Execute(os.Stdout,1)
  25. text="学生列表: {{ range .}} {{.}}| {{ end }}" //内部的.是range 外部的. 每次遍历的元素
  26. tpl,_=template.New("test").Parse(text)
  27. tpl,Execute(os.Stdout,[]string{"aaa","bbb","cccc"})
  28. text="第一个元素: {{ index . 0}}" //打印序列内索引为0的元素
  29. tpl,_=template.New("test").Parse(text)
  30. tpl.Execute(os.Stdout,[]string{"aaa","bbb","cccc"})
  31. text="name: {{ .name }} addr: {{ .addr }}" //打印map类型或结构体的元素
  32. tpl,_=template.New("test").Parse(text)
  33. tpl.Execute(os.Stdout,map[string]string{"name":""})
  34. tpl.Execute(os.Stdout,struct{Name,Addr string}{"xxx","yyy"}) //结构体也可以缩写成这样
  35. tpl,_:=tpl.ParseFiles("user.html") //解析文件
  36. tpl.ExecuteTemplate(os.Stdout,"user.html",struct{Name,Addr string}{"xxx","yyy"}) //通过解析文件执行

文档更新时间: 2022-03-19 13:06   作者:张尚