Versions Compared
compared with
Key
- This line was added.
- This line was removed.
- Formatting was changed.
模板布局
gview
模板引擎支持两种layout
模板布局方式:
...
define
+template
方式
...
include
模板嵌入方式
这两种方式均支持对模板变量的传入。
define
+ template
由于gview
底层采用了ParseFiles
方式批量解析模板文件,因此可以使用define
标签定义模板内容块,通过template
标签在其他任意的模板文件中引入指定的模板内容块。template
标签支持跨模板引用,也就是说define
标签定义的模板内容块可能是在其他模板文件中,template
也可以随意引入。
Note |
---|
注意: |
...
|
使用示例:
...
Image Added
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.go
package main
...
import ( "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" )
...
func main() { s := g.Server() s.BindHandler("/", func(r *ghttp.Request) { r.Response.WriteTpl("layout.html", g.Map{ "header": "This is header", "container": "This is container", "footer": "This is footer", }) }) s.SetPort(8199) s.Run() }
...
执行后,访问 http://127.0.0.1:8199 结果如下:
...
Image Added
include
模板嵌入
当然我们也可以使用include
标签来实现页面布局。
Note |
---|
注意,为嵌套的子模板传递模板变量时,应当使用: |
使用示例:
...
Image Added
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
...
copy<h1>MAIN2</h1>
main.go
package main
...
import ( "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/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() }
...
...
Image Added
...
Image Added
Panel | ||
---|---|---|
| ||
|