1 回答
TA贡献1834条经验 获得超8个赞
你确实可以!您只需将变量传递到嵌套模板中。
您引用的文档是关于模板如何无法从 go 过程中读取变量的,除非您明确将它们传入。
同样,嵌套模板将获取您传递给它们的任何内容,仅此而已。
来自https://golang.org/pkg/text/template/#hdr-Actions
{{template "name"}}
The template with the specified name is executed with nil data.
{{template "name" pipeline}}
The template with the specified name is executed with dot set
to the value of the pipeline.
下面是一个根据您的提示轻而易举的简单示例:
package main
import (
"os"
"text/template"
)
func main() {
var animals = map[string]string{
"spirit_animal": "cat",
"spirit_predator": "dog",
}
const letter = `
{{define "echo"}}Inside a template, I echo what you say: {{.}}{{end}}
{{define "predator"}}Inside a template, I know that your predator is: {{.spirit_predator}}{{end}}
Your spirit animal is: {{.spirit_animal}}
{{template "predator" . }}
{{template "echo" .spirit_animal }}`
t := template.Must(template.New("letter").Parse(letter))
_ = t.Execute(os.Stdout, animals)
}
https://play.golang.org/p/3X7IQasWlsR
- 1 回答
- 0 关注
- 358 浏览
添加回答
举报
