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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值