- 模板布局
define+templateinclude模板嵌入
模板布局
gview模板引擎支持两种layout模板布局方式:define + template方式 和 include模板嵌入方式。
define + template
由于gview底层采用了ParseFiles方式批量解析模板文件,因此可以使用define标签定义模板内容块,通过template标签在其他任意的模板文件中引入指定的模板内容块。template标签支持跨模板引用,也就是说define标签定义的模板内容块可能是在其他模板文件中,template也可以随意引入。
使用示例:

layout.html<!DOCTYPE html><html><head><title>GoFrame Layout</title>{{template "header"}}</head><body><div class="container">{{template "container"}}</div><div class="footer">{{template "footer"}}</div></body></html>
header.html{{define "header"}}<h1>HEADER</h1>{{end}}
container.html{{define "container"}}<h1>CONTAINER</h1>{{end}}
footer.html{{define "footer"}}<h1>FOOTER</h1>{{end}}
main.gopackage mainimport ("github.com/gogf/gf/g""github.com/gogf/gf/g/net/ghttp")func main() {s := g.Server()s.BindHandler("/", func(r *ghttp.Request) {r.Response.WriteTpl("layout.html", nil)})s.SetPort(8199)s.Run()}
执行后,访问 http://127.0.0.1:8199 结果如下:

include模板嵌入
当然我们也可以使用include标签来实现页面布局。
使用示例:

layout.html{{include "header.html" .}}{{include .mainTpl .}}{{include "footer.html" .}}
header.html<h1>HEADER</h1>
footer.html<h1>FOOTER</h1>
main1.html<h1>MAIN1</h1>
main2.html<h1>MAIN2</h1>
main.gopackage mainimport ("github.com/gogf/gf/g""github.com/gogf/gf/g/net/ghttp")func main() {s := g.Server()s.BindHandler("/main1", func(r *ghttp.Request) {r.Response.WriteTpl("layout.html", g.Map{"mainTpl": "main/main1.html",})})s.BindHandler("/main2", func(r *ghttp.Request) {r.Response.WriteTpl("layout.html", g.Map{"mainTpl": "main/main2.html",})})s.SetPort(8199)s.Run()}
执行后,访问不同的路由地址,将会看到不同的结果:
http://127.0.0.1:8199/main1
http://127.0.0.1:8199/main2
