Golang中的模板继承

问题描述 投票:0回答:1

我正在尝试将 base 模板继承到我的 *home 页面文件中 Golang

我的目录结构:

project_root
  /templates
    /layouts
        base.layout.html
    /pages
        home.page.html

Gin路由器配置:

router.LoadHTMLGlob("./templates/layouts/*.layout.html")
router.LoadHTMLGlob("./templates/pages/*.page.html")

templates/layouts/base.layout.html 文件:

{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.Title}}</title>
</head>
<body>
    {{block "content" .}} {{end}}
</body>
</html>
{{end}}

templates/pages/ho,e.page.html 文件:

{{template "base" .}}

{{define "page-title"}}
    Home
{{end}}
{{end}}

我收到的错误:

错误#01:html/template:home.page.html:1:11:没有这样的模板“base”

注意:如果我删除了继承,主页会正常加载。

go go-templates
1个回答
0
投票

不要对

LoadHTMLGlob

进行 2 个不同的调用,而只需使用:

router.LoadHTMLGlob("./templates/**/*.html")

说明

您的问题是由于第二次调用

LoadHTMLGlob

完全覆盖了第一次调用已加载的内容引起的。这是因为:


    LoadHTMLGlob
  • 调用
    engine.SetHTMLTemplate(templ)
    https://github.com/gin-gonic/gin/blob/v1.9.1/gin.go#L263
  • SetHTMLTemplate
  • 分配
    engine.HTMLRender
    https://github.com/gin-gonic/gin/blob/v1.9.1/gin.go#L284
  • 因此,代码中两次调用
engine.HTMLRender

时,

LoadHTMLGlob
的内容与仅调用
LoadHTMLGlob("./templates/pages/*.page.html")
时的内容相同。所以
base
不存在是正常的,因为它是在
./templates/layouts/*.layout.html
中定义的。
这就是为什么您应该只拨打一次电话至 

LoadHTMLGlob

关于您的模板

另外,我不知道你想在这里实现什么,但是

page-title

中定义的

home.page.html
没有在
base.layout.html
中使用,而是用
.Title
代替。如果您的 Go 代码是:
router.GET("/", func(c *gin.Context) {
    c.HTML(http.StatusOK, "home.page.html", gin.H{})
})

然后您可以在布局中使用 
page-title

(而不是

.Title
):
-    <title>{{.Title}}</title>
+    <title>{{block "page-title" .}} {{end}}</title>

并在您的主页中定义它,如下所示:

{{template "base" .}} {{define "page-title"}} Home {{end}} {{define "content"}} Welcome to my website! {{end}}

访问
/

时,您将看到一个标题为

Home
、正文内容为
Welcome to my website!
的网页。
    

© www.soinside.com 2019 - 2024. All rights reserved.