Golang向Templates 插入對象的值

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
相關文章
相關標籤/搜索