如何使用golang htmltemplate的基本模板文件?

如何使用golang htmltemplate的基本模板文件?,第1张

概述有gin-gonic网络应用程序. 有3个文件: 1)base.html – 基本布局文件 <!DOCTYPE html><html lang="en"><body>header...{{template "content" .}}footer...</body></html> 2)page1.html,用于/ page1 {{define "content"}}<div> 有gin-gonic网络应用程序.

有3个文件:

1)base.HTML – 基本布局文件

<!DOCTYPE HTML><HTML lang="en"><body>header...{{template "content" .}}footer...</body></HTML>

2)page1.HTML,用于/ page1

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

3)page2.HTML,用于/ page2

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

问题是/ page1和/ page2使用一个模板 – page2.HTML.我认为我对这种结构有误解:{{define“content”}},{{template“base.HTML”}}.

请问,您能举例说明如何在golang中使用基本布局吗?

解决方法 只要您将模板与“内容”一起解析,就可以使用base.HTML,如下所示:

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

然后Parsefiles与(“your-page.HTML”,“base.HTML”)和ExecuteTemplate与您的上下文.

tmpl,err := template.New("").Parsefiles("page1.HTML","base.HTML")// check your errerr = tmpl.ExecuteTemplate(w,"base",yourContext)
总结

以上是内存溢出为你收集整理的如何使用golang html / template的基本模板文件?全部内容,希望文章能够帮你解决如何使用golang html / template的基本模板文件?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1265598.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存