当好几个页面的样式都一样,但是内容不一样的话,只需要定义一个根模板,然后让其他模板继承这个根模板,然后自己定义内容即可
根模板
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>模板继承</title>
<style>
* {
margin: 0;
}
.nav {
height: 50px;
width: 100%;
position: fixed;
top: 0;
background-color: burlywood;
}
.main {
margin-top: 50px;
}
.menu {
width: 20%;
height: 100%;
position: fixed;
left: 0;
background-color: cornflowerblue;
}
.center {
text-align: center;
}
</style>
</head>
<body>
<div class="nav"></div>
<div class="main">
<div class="menu"></div>
<div class="content center">
<!-- 这里用来让其他模板继承,模板名称叫content,也会传过去个参数. -->
{{block "content" .}}{{end}}
</div>
</div>
</body>
</html>
子模版1
<!--继承根模板-->
{{template "base.tmpl" .}}
<!--重新定义块模板-->
{{define "content"}}
<h1>这是home2页面</h1>
<p>hello,{{ . }}</p>
{{end}}
子模版2
<!--继承根模板-->
{{template "base.tmpl" .}}
<!--重新定义块模板-->
{{define "content"}}
<h1>这是index2页面</h1>
<p>hello,{{ . }}</p>
{{end}}
解析模板
func index2(w http.ResponseWriter,r *http.Request) {
//顺序不能错,先根模板,再子模版
t,err := template.ParseFiles("./templates/base.tmpl","./templates/index2.tmpl")
if err != nil {
fmt.Printf("parse template failed, err %v\n", err)
return
}
name := "小王子"
t.ExecuteTemplate(w,"index2.tmpl",name)
}
func home2(w http.ResponseWriter,r *http.Request) {
t,err := template.ParseFiles("./templates/base.tmpl","./templates/home2.tmpl")
if err != nil {
fmt.Printf("parse template failed, err %v\n", err)
return
}
name := "小王子"
t.ExecuteTemplate(w,"home2.tmpl",name)
}
main函数
func main() {
http.HandleFunc("/index2",index2)
http.HandleFunc("/home2",home2)
err := http.ListenAndServe(":9090", nil)
if err != nil {
fmt.Printf("HTTP server start failed,err : %v", err)
return
}
}
结果