【发布时间】:2020-06-19 04:34:57
【问题描述】:
我正在为我的网络应用程序使用 Go gin gonic。如何在 1 页中多次使用同一个模板文件,并将不同的变量传递给模板。
segment.tmpl
{{ define "segment" }}
<div>{{ .Variable }}</div>
{{ end }}
layout.tmpl
<!DOCTYPE HTML>
<html>
<body>
{{ template "segment . }} #with a variable 1
{{ template "segment . }} #with different variable
{{ template "segment . }} #another same template with another
</body>
</html>
main.go
r.GET("/home/", func(c *gin.Context) {
tmpl := template.Must(template.ParseFiles("templates/layout.tmpl", "templates/product_add.tmpl", "templates/segment.tmpl")
r.SetHTMLTemplate(tmpl)
c.HTML(200, "layout", gin.H {
"Variable1": "var1",
"variable2": "var2",
})
}
如何在“主页”页面中多次使用segment.tmpl 并将不同类型的变量传递给segment.tmpl? 我到处搜索,一无所获,最接近的是template.Clone,但仍然找不到它的任何例子。
【问题讨论】:
-
{{ template "segment" .Variable1 }}然后在段中只需执行{{ . }}即可获得Variable1的值。 -
哇,非常感谢,正是我需要的,抱歉刚刚迁移到 Go。请把它写成答案,我会接受这个作为答案。谢谢。
标签: go go-templates go-gin