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 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。