package main
import "text/template"
func main(){
//
// 解析模板 字符串
text:="我的名字叫{{.}}" // {{.}} 叫占位符
tpl,err:=template.New("test").Parse(text) //先new一个对象
if err !=nil{
fmt.Println(err)
}
tpl.Execute(os.Stdout,"kk") //根据tpl进行执行
tpl.Execute(os.Stdout,1)
tpl.Execute(os.Stdout,true)
tpl.Execute(os.Stdout,[]int{1,2,3})
tpl.Execute(os.Stdout,map[string]string{"1":"1"})
text = "性别:{{ if . }} 男 {{ else }} 女 {{ end }}\n" //if 条件判断
}
tpl,_=template.New("test").Parse(text)
tpl.Execute(os.Stdout,false)
text = "性别:{{ if =. }} 男 {{ else }} 女 {{ end }}\n" // 这种条件判断的语法是不支持的,"=" 可是使用 “eq”表示
// gt >, lt < , gte >=, lte <=, eq=, neq!=
text = "性别:{{ if eq 1 . }} 男 {{ else }} 女 {{ end }}\n" //if 条件判断
tpl,_=template.New("test").Parse(text)
tpl.Execute(os.Stdout,1)
text="学生列表: {{ range .}} {{.}}| {{ end }}" //内部的.是range 外部的. 每次遍历的元素
tpl,_=template.New("test").Parse(text)
tpl,Execute(os.Stdout,[]string{"aaa","bbb","cccc"})
text="第一个元素: {{ index . 0}}" //打印序列内索引为0的元素
tpl,_=template.New("test").Parse(text)
tpl.Execute(os.Stdout,[]string{"aaa","bbb","cccc"})
text="name: {{ .name }} addr: {{ .addr }}" //打印map类型或结构体的元素
tpl,_=template.New("test").Parse(text)
tpl.Execute(os.Stdout,map[string]string{"name":""})
tpl.Execute(os.Stdout,struct{Name,Addr string}{"xxx","yyy"}) //结构体也可以缩写成这样
tpl,_:=tpl.ParseFiles("user.html") //解析文件
tpl.ExecuteTemplate(os.Stdout,"user.html",struct{Name,Addr string}{"xxx","yyy"}) //通过解析文件执行
文档更新时间: 2022-03-19 13:06 作者:张尚