Search code examples
gogo-templatesgo-gin

How to use templates in Go Gin for dynamic content


I have a simple Go / Gin web app. I need to put some dynamic content in html template.

For e.g. I have a few tables (the number is dynamic) with a few rows (the number is dynamic). I need to put them in html template. Is there any way to combine templates in code? I'd prefer to use templates rather than build tables in the code.

I've checked a tutorial https://github.com/gin-gonic/gin but it is not covered there.


Solution

  • You can use define to define partials and template to mix multiple HTML partials.

    package main
    
    import (
        "html/template"
    
        "github.com/gin-gonic/gin"
    )
    
    var (
        partial1 = `{{define "elm1"}}<div>element1</div>{{end}}`
        partial2 = `{{define "elm2"}}<div>element2</div>{{end}}`
        body     = `{{template "elm1"}}{{template "elm2"}}`
    )
    
    func main() {
        // Or use `ParseFiles` to parse tmpl files instead 
        t := template.Must(template.New("elements").Parse(body))
    
        app := gin.Default()
        app.GET("/", func(c *gin.Context) {
            c.HTML(200, "elements", nil)
        })
        app.Run(":8000")
    }
    

    This is a good place to read https://gohugo.io/templates/go-templates/