1 回答

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
你確實(shí)可以!您只需將變量傳遞到嵌套模板中。
您引用的文檔是關(guān)于模板如何無(wú)法從 go 過(guò)程中讀取變量的,除非您明確將它們傳入。
同樣,嵌套模板將獲取您傳遞給它們的任何內(nèi)容,僅此而已。
來(lái)自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.
下面是一個(gè)根據(jù)您的提示輕而易舉的簡(jiǎn)單示例:
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 關(guān)注
- 314 瀏覽
添加回答
舉報(bào)