如何解决如何在 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")
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。