Search code examples
gogo-templatesgo-gin

How to render HTML Template In Gin Gonic (Golang)?


I am trying to create an HTML template on Golang using Gin Gonic. but there are problems when rendering the template that I made to produce a web view (the result is blank). Is there something wrong with my code? i tried to read gin gonic documentation but it can't solve my problem.

/workspace
|- main.go
|-web
  |-assets
  |-base
     | - header.html
     | - footer.html

  |-pages
    |-about.html

here is sample main file

import (
    "log"
    "net/http"

    "github.com/getsentry/sentry-go"
    "github.com/gin-gonic/gin"
    "html/template"
)


func main() {
    router := gin.Default()
    html := template.Must(template.ParseFiles("web/base/footer.html", "web/base/header.html"))
    router.SetHTMLTemplate(html)
    router.LoadHTMLGlob("web/pages/*")

    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "about.html", gin.H{
            "title": "Main website",
        })
    })
    router.Run(":8000")

}

Here my header.html file

{{ define "Header" }}
<head>
    <title>Example</title>
</head>
{{end}}

my footer.html

{{ define "Footer" }}
<script>
    
</script>
{{end}}

and this my about.html

{{define "about"}}
<html>
   {{ template "Header" }}
   <body>
       About me
       {{ template "Footer" }}
   </body
</html>

Thanks for advance


Solution

  • First put every template of same root template folder like:

    /workspace
    |- main.go
    |-web
      |-assets
      |-templates
        |-base
           | - header.html
           | - footer.html
        |-pages
          |-about.html
    

    Now set gin to load all templates from that root folder:

    func main() {
        router := gin.Default()
        router.LoadHTMLGlob("templates/**/*")
    
        router.GET("/index", func(c *gin.Context) {
            c.HTML(http.StatusOK, "about.html", gin.H{
                "title": "Main website",
            })
        })
        router.Run(":8000")
    
    }
    

    As you define the template name about you need to use it in the handler:

    func main() {
        router := gin.Default()
        router.LoadHTMLGlob("templates/**/*")
    
        router.GET("/index", func(c *gin.Context) {
            c.HTML(http.StatusOK, "about", gin.H{
                "title": "Main website",
            })
        })
        router.Run(":8000")
    
    }