Go对象能够插入到template中,而后把对象的值表如今template中,你能够一层层的分解这个对象,去找他的子字段,当前对象用'.'来表示,因此当当前对象是一个string的时候,你能够用{{.}}。这个包默认使用fmt包来把插入的对象转成stringhtml
插入某个对象字段的值,咱们在字段名字前面加上一个'.'前缀就能够了,例如咱们定义一个struct数组
type Person struct { Name string Age int Emails []string Jobs []*Jobs }
咱们能够经过code
The name is {{.Name}}. The age is {{.Age}}.
来插入Person对象,Name和Age的值。
咱们能够经过range来遍历一个数组或者其余列表,若是咱们要遍历Person的Email对象,咱们能够htm
{{range .Emails}} ... {{end}}
上面的Job是这么定义的对象
type Job struct { Employer string Role string }
咱们想访问Person的job,咱们能够经过{{range .Jobs}},经过 {{with ...}} ... {{end}} 能够把Jobs切换为当前对象,那么{{.}}就表明的是Jobsstring
{{with .Jobs}} {{range .}} An employer is {{.Employer}} and the role is {{.Role}} {{end}} {{end}}
你能够用这个来处理任何字段,不单单是数据类型。说了这么多没用的,仍是上代码吧,从代码就能够很清楚的看出tempalte的用法it
package main import ( "fmt" "html/template" "os" ) type Person struct { Name string Age int Emails []string Jobs []*Job } type Job struct { Employer string Role string } const templ = `The name is {{.Name}}. The age is {{.Age}}. {{range .Emails}} An email is {{.}} {{end}} {{with .Jobs}} {{range .}} An employer is {{.Employer}} and the role is {{.Role}} {{end}} {{end}} ` func main() { job1 := Job{Employer: "Monash", Role: "Honorary"} job2 := Job{Employer: "Box Hill", Role: "Head of HE"} person := Person{ Name: "jan", Age: 50, Emails: []string{"jan@newmarch.name", "jan.newmarch@gmail.com"}, Jobs: []*Job{&job1, &job2}, } t := template.New("Person template") t, err := t.Parse(templ) checkError(err) err = t.Execute(os.Stdout, person) checkError(err) } func checkError(err error) { if err != nil { fmt.Println("Fatal error ", err.Error()) os.Exit(1) } }
程序输出:class
The name is jan. The age is 50. An email is jan@newmarch.name An email is jan.newmarch@gmail.com An employer is Monash and the role is Honorary An employer is Box Hill and the role is Head of HE