go语言web开发15 - beego模板之layout设计
网页的有些部分是固定的,如网页导航和页脚导航信息等,如果每个网页都写一遍 “固定的部分” 难免比较麻烦,这里就可以用到layout设计,什么是layout设计那?请看下面示例。
layout设计示例
1、路由配置如下
beego.Router("/layout", &controllers.LayoutController{})
2、Controller内容如下
func (c *LayoutController) Get() { c.Layout = "base.html" // 3.指定layout模板 c.LayoutSections = make(map[string]string) // 4.指定多个layout模板文件(用key名字替换模板里的内容) c.LayoutSections["layout_header"] = "test_layout/layout_header.html" c.LayoutSections["layout_foot"] = "test_layout/layout_foot.html" c.Data["sitename"] = "优选工具" // 2.往请求模板文件里传数据 c.TplName = "test_layout/test_layout.html" // 1.指定当前请求的模板文件 }
(2.1)、路由对应的模板文件内容如下
<p>此内容为模板文件内容</p>
{{.sitename}} <br>
(2.2)、layout模板(base.html)内容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {{.layout_header}} <!-- 这里替换:test_layout/layout_header.html文件里的内容 --> </head> <body> <h1>顶部导航:LayOut设计</h1> {{.LayoutContent}}<br> <!-- test_layout.html(请求模板)里的内容在这里替换 --> <p>底部信息</p> {{.layout_foot}} <!-- 这里替换:test_layout/layout_foot.html里的内容 --> </body> </html>
(2.3)、test_layout/layout_header.html内容如下
<link rel="stylesheet" href="/static/css/static_test.css"> <script src="/static/js/static_test.js"></script>
(2.4)、test_layout/layout_foot.html内容如下
<p>xxx科技有限公司 版权所有</p>
3、浏览器访问