dongwu9647 2019-03-15 21:07
浏览 166
已采纳

Golang模板无法加载

I started to write a Gin application and my project tree looks like

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

In main.go I load templates and there is no error

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

I define templates

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

And I nest them

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

But when I try to use them, I get empty output

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

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

[Edit] Function that executes the template:

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

Full-code can be found on github

  • 写回答

1条回答 默认 最新

  • doupang9614 2019-03-16 04:57
    关注

    router.LoadHTMLGlob and template.ParseFiles are two separate approaches to deal with templates. The template returned by ParseFiles has no knowledge of the templates loaded by LoadHTMLGlob. Once you decide to use LoadHTMLGlob you should then use c.HTML to render your templates. And the name argument to this c.HTML method would be either the name specified in a {{define "name"}} action or the base name of the template file (including the extention I believe).

    So in your case you should probably do something like this:

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

    More examples can be found here: https://gin-gonic.com/docs/examples/html-rendering/

    Keep in mind that LoadHTMLGlob relies on template.ParseGlob which states:

    When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

    That means that if you want all of your templates to be accessible through c.HTML you need to make sure that they either have unique base names or they need to contain the {{ define "name"}} action.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c