1、简单实例
package main import ( "os" "text/template" ) func main() { const xichen = `Hello World {{.}}` M := template.New("") M.Parse(di) M.Execute(os.Stdout, "曦晨") }
package main import ( "os" "text/template" ) func main() { const 曦晨 = `{{range .}}Hello World :{{.}} {{end}}` var list []string = []string{"曦晨", "李四", "张三"} M := template.New("") M.Parse(曦晨) M.Execute(os.Stdout, list) }
package main import ( "os" "text/template" ) type x struct { A姓名, B级别, C性别 string } const M = `姓名:{{.A姓名}} 级别:{{.B级别}} 性别:{{.C性别}} ` func main() { var info = x{"曦晨", "1", "男"} tm := template.New("") tm.Parse(M) tm.Execute(os.Stdout, info) }4、条件语句使用
package main import ( "os" "text/template" ) type x struct { A姓名, B级别, C性别 string } const M = `{{range .}}{{if .B级别}}姓名:{{.A姓名}} 性别:{{.C性别}}{{end}} {{end}}` func main() { var di = []x{{"曦晨", "1", "男"}, {"晨曦", "2", "女"}, {"曦love晨", "", "男love女"}} t := template.New("") template.Must(t.Parse(M)) t.Execute(os.Stdout, di) }5、变量使用
package main import ( "os" "text/template" ) type x struct { A姓名, B级别, C性别 string } const M = `{{range $k,$v := .}}信息:{{$v.A姓名}} {{end}}` func main() { var di = []x{{"曦晨", "1", "男"}, {"晨曦", "2", "女"}} t := template.New("") t.Parse(M) t.Execute(os.Stdout, di) }6、函数的使用
package main import ( "os" "text/template" ) type x struct { A姓名, B级别, C性别 string } const M = `{{range $k,$v := .}}{{$k|Func|print}}{{$v.A姓名}} // "|"作用相当于管道,用来传值 {{end}}` func main() { var di = []x{{"曦晨", "1", "男"}, {"晨曦", "2", "女"}} Func := template.FuncMap{"Func": ce} //把定义的函数实例 t := template.New("") t.Funcs(Func) //注册要使用的函数 t.Parse(M) t.Execute(os.Stdout, di) } func ce(i int) string { return "姓名:" }
原文地址:http://blog.csdn.net/fyxichen/article/details/45740143