This is a creation in Article, where the information may have evolved or changed.
Take the time to go to the Text/templete template finishing study, now summarized under.
Steps
1. Define data types
type Opt struct{ Name string Age int Score float32}oneOpt{"xiao chao",26,90}twoOpt{"xiao er",29,89}
2. Create a template
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. Parsing templates
t1,_ = t1.Parse(one_str) t2,_ = t2.Parse(two_str)
4. Execute the template
t1.ExecuteTemplate(os.Stdout,"one1",one) println("\n") t2.ExecuteTemplate(os.Stdout,"two2",two)
Full code:
PackageMainimport ("OS" "Text/template")typeOpt struct{NamestringAge int score Float32}func main () {/* Stu: = opt{"Zhao Zi Long", -, About} Tmpl, err: = template. New ("Stu"). Parse ("Hello, name:{{." name}},age:{{. age}},score:{{. Score}} ")//Create a template that contains"Hello, {{.}}"TMP2,ERR2: = template. New (""). Executetemplate ()ifErr! =Nil{Panic (err)} err = Tmpl. Execute (OS. Stdout, Stu)//WillstringWith template composition, the contents of the variable name are replaced by {{.}} The results of the synthesis are placedOS. StdOut.ifErr! =Nil{Panic (ERR)} */One: = opt{"Xiao Chao", -, -}: = opt{"Xiao er", in, the} 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", both)}