dousuochu7291 2016-04-14 08:44
浏览 104
已采纳

如何将基本模板文件用于golang html / template?

Have gin-gonic web app.

There are 3 files:

1) base.html -- base layout file

<!DOCTYPE html>
<html lang="en">
<body>

header...

{{template "content" .}}

footer...

</body>
</html>

2) page1.html, for /page1

{{define "content"}}
<div>
    <h1>Page1</h1>
</div>
{{end}}
{{template "base.html"}}

3) page2.html, for /page2

{{define "content"}}
<div>
    <h1>Page2</h1>
</div>
{{end}}
{{template "base.html"}}

The problem is that /page1 and /page2 use one template - page2.html. I think that I have misunderstanding of such constructions: {{define "content"}}, {{template "base.html"}}.

Please, can you show an example how to use base layouts in golang?

  • 写回答

1条回答 默认 最新

  • douzen1880 2016-04-15 09:44
    关注

    You can use the base.html as long as you parse the template along with your "content", like so:

    base.html

    {{define "base"}}
    <!DOCTYPE html>
    <html lang="en">
    <body>
    
    header...
    
    {{template "content" .}}
    
    footer...
    
    </body>
    </html>
    {{end}}
    

    page1.html

    {{define "content"}}
    I'm page 1
    {{end}}
    

    page2.html

    {{define "content"}}
    I'm page 2
    {{end}}
    

    then ParseFiles with ("your-page.html", "base.html"), and ExecuteTemplate with your context.

    tmpl, err := template.New("").ParseFiles("page1.html", "base.html")
    // check your err
    err = tmpl.ExecuteTemplate(w, "base", yourContext)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看