golang模版取变量值

{{.deployPath}} 看起来像 Go 的 text/templatehtml/template 模板语法。在模板里,{{.deployPath}} 表示取传入模板的数据结构中的 deployPath 字段或 key。

1. 用 struct 传值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import (
"os"
"text/template"
)

type Data struct {
DeployPath string
}

func main() {
tpl := `部署路径是: {{.DeployPath}}`
data := Data{DeployPath: "/opt/app"}

t := template.Must(template.New("test").Parse(tpl))
t.Execute(os.Stdout, data)
}

输出:

部署路径是: /opt/app

2. 用 map[string]interface{} 传值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import (
"os"
"text/template"
)

func main() {
tpl := `部署路径是: {{.deployPath}}`
data := map[string]interface{}{
"deployPath": "/data/service",
}

t := template.Must(template.New("test").Parse(tpl))
t.Execute(os.Stdout, data)
}

输出:

部署路径是: /data/service

🔑 关键点:

  • 如果你用 struct,字段必须是 导出字段(首字母大写),否则模板访问不到。
  • 如果你用 map,key 可以是小写,模板里要严格匹配。