網頁

2023/10/30

Golang template 取得parent pipeline的值

Golang text/template可使用$符號存取父pipeline的物件。


範例

例如下面在模板range範圍中,使用$.Name取得資料的根,即Department.Name的值。

main.go

package main

import (
    "os"
    "text/template"
)

type Department struct {
    Name      string
    Employees []Employee
}

type Employee struct {
    Name string
    Age  int
}

func main() {
    text := `Department: {{.Name}}
Employees:
{{range .Employees}}    Name:{{.Name}} - {{$.Name}}, Age:{{.Age}}
{{end}}`
    t := template.Must(template.New("demo").Parse(text))

    data := Department{
        Name: "RD",
        Employees: []Employee{
            {"John", 33},
            {"Mary", 28},
        },
    }

    err := t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}


測試

執行印出以下:

Department: RD
Employees:
    Name:John - RD, Age:33
    Name:Mary - RD, Age:28


沒有留言:

張貼留言