Search code examples
gogo-templatesgo-gin

Use the same template with different param/variables in 1 page


I am using Go gin gonic for my web app. How do I use the same template file multiple times in 1 page with different variables passed to the template.

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",
    })
}

How do I use segment.tmpl multiple times in the page "home" and passing different kind of variables to the segment.tmpl? I have searched everywhere and have found nothing, the closest thing is template.Clone, but still couldn't find any examples of it.


Solution

  • You can pass any value as the "pipeline" to the template, it doesn't have to be the "dot", i.e. you could pass the result of a function call, or, in this case, the result of accessing a map's value.

    {{ template "segment" .Variable1 }}
    

    and then inside the template "segment" you can refer to the pipeline using the dot, i.e. {{ . }}.


    segment.tmpl

    {{ define "segment" }}
        <div>{{ . }}</div>
    {{ end }}
    

    layout.tmpl

    <!DOCTYPE HTML>
    <html>
    <body>
        {{ template "segment .Variable1 }}
        {{ template "segment .Variable2 }}
        {{ template "segment .AnotherVariable }}
    </body>
    </html>