Golang向Templates 插入对象的值

Go对象可以插入到template中,然后把对象的值表现在template中,你可以一层层的分解这个对象,去找他的子字段,当前对象用'.'来表示,所以当当前对象是一个string的时候,你可以用{{.}}。这个包默认使用fmt包来把插入的对象转成string

插入某个对象字段的值,我们在字段名字前面加上一个'.'前缀就可以了,例如我们定义一个struct

type Person struct {
        Name      string
        Age       int
        Emails     []string
        Jobs       []*Jobs
}

我们可以通过

The name is {{.Name}}.
The age is {{.Age}}.

来插入Person对象,Name和Age的值。
我们可以通过range来遍历一个数组或者其他列表,如果我们要遍历Person的Email对象,我们可以

{{range .Emails}}
        ...
{{end}}

上面的Job是这么定义的

type Job struct {
    Employer string
    Role     string
}

我们想访问Person的job,我们可以通过{{range .Jobs}},通过 {{with ...}} ... {{end}} 可以把Jobs切换为当前对象,那么{{.}}就代表的是Jobs

{{with .Jobs}}
    {{range .}}
        An employer is {{.Employer}}
        and the role is {{.Role}}
    {{end}}
{{end}}

你可以用这个来处理任何字段,不仅仅是数据类型。说了这么多没用的,还是上代码吧,从代码就可以很清楚的看出tempalte的用法

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)
	}
}

程序输出:


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
    

posted @ 2014-12-01 20:37  纵酒挥刀斩人头  阅读(688)  评论(0编辑  收藏  举报