如何在 Gin Gonic (Golang) 中呈现 HTML 模板?

问题描述

我正在尝试使用 Gin Gonic 在 Golang 上创建 HTML 模板。但是在渲染我为生成 Web 视图而制作的模板时出现问题(结果为空白)。我的代码有问题吗?我试图阅读 gin gonic 文档,但它无法解决我的问题。

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

  |-pages
    |-about.html

这里是示例主文件

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

}

这里是我的 header.html 文件

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

我的页脚.html

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

这是我的 about.html

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

感谢提前

解决方法

首先将每个模板放在同一个根模板文件夹中,例如:

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

现在设置 gin 从该根文件夹加载所有模板:

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

}

当您定义模板名称 about 时,您需要在处理程序中使用它:

func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/**/*")

    router.GET("/index","about",})
    })
    router.Run(":8000")

}