go - 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上找到
解决方案
router.LoadHTMLGlob
并且template.ParseFiles
是处理模板的两种不同方法。返回的模板ParseFiles
不知道LoadHTMLGlob
. 一旦你决定使用LoadHTMLGlob
,你就应该使用它c.HTML
来渲染你的模板。name
此c.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"}}
操作。
推荐阅读
- javascript - matter.js:有什么方法可以为我的精灵设置动画
- java - 读取值表格 excel 单行多列
- python - 如何将列表的行合并成短语(帮助完成代码)?
- reactjs - 使用 nginx 修改 spa index.html 元标记
- r - r中每个类别的条形图平均值
- javascript - 没有不同类的 Puppeteer Scraping Tables
- c++ - 来自具有 OpenCV 4.20 构建的网络摄像头的不同图像(MSVC 2019(良好图像)和 MinGW(奇怪图像))
- php - Apache PHP 脚本上的 XSS 漏洞
- javascript - 导入文本文件的 Highcharts 区域功能
- c++ - 使用虚函数而不覆盖该虚函数的目的