在 1 个页面中使用不同 param/variables 的相同模板
Use the same template with different param/variables in 1 page
我正在为我的网络应用程序使用 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",
})
}
如何在页面 "home" 中多次使用 segment.tmpl 并将不同类型的变量传递给 segment.tmpl?
我到处找遍了,一无所获,最接近的是template.Clone,但仍然找不到任何例子。
您可以将任何值作为 "pipeline" 传递给模板,它不一定是 "dot",即您可以传递函数调用的结果,或者,在此case,访问地图值的结果。
{{ template "segment" .Variable1 }}
然后在模板中 "segment"
您可以使用点来引用管道,即 {{ . }}
.
segment.tmpl
{{ define "segment" }}
<div>{{ . }}</div>
{{ end }}
layout.tmpl
<!DOCTYPE HTML>
<html>
<body>
{{ template "segment .Variable1 }}
{{ template "segment .Variable2 }}
{{ template "segment .AnotherVariable }}
</body>
</html>
我正在为我的网络应用程序使用 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",
})
}
如何在页面 "home" 中多次使用 segment.tmpl 并将不同类型的变量传递给 segment.tmpl? 我到处找遍了,一无所获,最接近的是template.Clone,但仍然找不到任何例子。
您可以将任何值作为 "pipeline" 传递给模板,它不一定是 "dot",即您可以传递函数调用的结果,或者,在此case,访问地图值的结果。
{{ template "segment" .Variable1 }}
然后在模板中 "segment"
您可以使用点来引用管道,即 {{ . }}
.
segment.tmpl
{{ define "segment" }}
<div>{{ . }}</div>
{{ end }}
layout.tmpl
<!DOCTYPE HTML>
<html>
<body>
{{ template "segment .Variable1 }}
{{ template "segment .Variable2 }}
{{ template "segment .AnotherVariable }}
</body>
</html>