首页 > 解决方案 > Golang 模板不会加载

问题描述

我开始编写一个 Gin 应用程序,我的项目树看起来像

-assets
--css
---{bootstrap}
-templates
--layouts
---footer.html
---head.html
---header.html
--book.html
-main.go

在 main.go 我加载模板并且没有错误

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

我定义模板

{{ define "head" }}
<head>
    //Head
</head>
 {{ end }}

我把它们嵌套

 {{ define "header" }}
 {{ template "head.html" . }}
 //HTML
 {{ end }}

但是当我尝试使用它们时,我得到空输出

 {{ template "header" . }}
 <h1>{{ .Title}}</h1>

 <h3>{{ .Author.Fullname}}</h3>

[编辑] 执行模板的函数:

func getBook(c *gin.Context) {
//DB stuff
var book models.Book
t, err := template.ParseFiles("templates/book.html")
if err != nil {
    log.Println(err)
}
t.Execute(c.Writer, book)
}

完整代码可以在github上找到

标签: gogo-templatesgo-gin

解决方案


router.LoadHTMLGlob并且template.ParseFiles是处理模板的两种不同方法。返回的模板ParseFiles不知道LoadHTMLGlob. 一旦你决定使用LoadHTMLGlob,你就应该使用它c.HTML来渲染你的模板。namec.HTML方法的参数可以是{{define "name"}} 操作中指定的名称,也可以是模板文件的基本名称(包括我认为的扩展名)。

因此,在您的情况下,您可能应该执行以下操作:

c.HTML(http.StatusOK, "book.html", book)

更多示例可以在这里找到:https ://gin-gonic.com/docs/examples/html-rendering/

请记住,这LoadHTMLGlob取决于template.ParseGlob哪些状态:

当解析不同目录中的多个同名文件时,最后提到的将是结果。

这意味着如果您希望所有模板都可以通过您访问,c.HTML您需要确保它们具有唯一的基本名称或者它们需要包含{{ define "name"}}操作。


推荐阅读