抽空把go 的text/templete模板整理学习了,现在总结下。
步骤
1、定义数据类型
type Opt struct{
Name string
Age int
Score float32
}
one := Opt{"xiao chao",26,90}
two := Opt{"xiao er",29,89}
2、建立模板
one_str := "one_str :my name is {{.Name}},and age is {{.Age}},my score is {{.Score}}."
two_str := "two_str :my name is {{.Name}},and age is {{.Age}},my score is {{.Score}}."
t1 := template.New("one1")
t2 := template.New("two2")
3、解析模板
t1,_ = t1.Parse(one_str)
t2,_ = t2.Parse(two_str)
4、执行模板
t1.ExecuteTemplate(os.Stdout,"one1",one)
println("\n")
t2.ExecuteTemplate(os.Stdout,"two2",two)
完整代码:
package main
import (
"os"
"text/template"
)
type Opt struct{
Name string
Age int
Score float32
}
func main() {
/*
stu := Opt{"zhao zi long",30,99}
tmpl, err := template.New("stu").Parse("hello, name:{{.Name}},age:{{.Age}},score:{{.Score}}") //建立一个模板,内容是"hello, {{.}}"
//tmp2,err2 := template.New("").ExecuteTemplate()
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, stu) //将string与模板合成,变量name的内容会替换掉{{.}}
//合成结果放到os.Stdout里
if err != nil {
panic(err)
}
*/
one := Opt{"xiao chao",26,90}
two := Opt{"xiao er",29,89}
one_str := "one_str :my name is {{.Name}},and age is {{.Age}},my score is {{.Score}}."
two_str := "two_str :my name is {{.Name}},and age is {{.Age}},my score is {{.Score}}."
t1 := template.New("one1")
t2 := template.New("two2")
t1,_ = t1.Parse(one_str)
t2,_ = t2.Parse(two_str)
t1.ExecuteTemplate(os.Stdout,"one1",one)
println("\n")
t2.ExecuteTemplate(os.Stdout,"two2",two)
}
有疑问加站长微信联系(非本文作者)