【问题标题】:Use the same template with different param/variables in 1 page在 1 页中使用具有不同参数/变量的相同模板
【发布时间】: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


【解决方案1】:

您可以将任何值作为“管道”传递给模板,它不必是“点”,即您可以传递函数调用的结果,或者在这种情况下,传递访问的结果地图的价值。

{{ 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>

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多