演示事例
Golang程序
package main
import (
"fmt"
"html/template"
"net/http"
)
func Func_index( w http.ResponseWriter , r *http.Request ){
// 定义模板
// 解析模板
t , err := template.ParseFiles("./templates/base.tmpl","./templates/index.tmpl")
if err != nil{
fmt.Printf("template Parse failed , err : %v\n",err)
return
}
// 渲染模板
name := "靓仔"
t.ExecuteTemplate(w,"index.tmpl",name)
}
func Func_home( w http.ResponseWriter , r *http.Request){
// 定义模板
// 解析模板
t , err := template.ParseFiles("./templates/base.tmpl","./templates/home.tmpl")
if err != nil{
fmt.Printf("template Parse failed , err : %v\n",err)
return
}
// 渲染模板
name := "靓仔"
t.ExecuteTemplate(w,"home.tmpl",name)
}
func main(){
http.HandleFunc("/index",Func_index)
http.HandleFunc("/home",Func_home)
err := http.ListenAndServe("127.0.0.1:9000",nil)
if err != nil{
fmt.Printf("http serve failed , err : %v\n",err)
return
}
}
上课笔记
template.ParseFiles("./templates/base.tmpl","./templates/home.tmpl")
按继承顺序,从根模板到子模板的顺序进行解析
t.ExecuteTemplate(w,"home.tmpl",name)
使用ExecuteTemplate
解析并指定相应的模板home.tmpl
,传入相应的参数name
base.tmpl
<!DOCTYPE html>
<html lang = "zh-CN">
<head>
<title>模板继承</title>
<style>
*{
margin: 0;
}
.nav{
height : 50px ;
width: 100%;
position: fixed;
top: 0;
background: cadetblue;
}
.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">
{{block "content" .}}{{end}}
</div>
</div>
</body>
</html>
上课笔记
{{block "content" .}}{{end}}
利用block
关键字来挖空替换的内容;
home.tmpl
{{/*继承根模板*/}}
{{ template "base.tmpl" . }}
{{/*重新定义块模板*/}}
{{define "content"}}
<h1>这是home页面</h1>
<p>hello {{.}}</p>
{{end}}
上课笔记
{{ template "base.tmpl" . }}
;继承时别忘了还需要把参数.
应继承;
{{define "content"}} ... {{end}}
:在...
相应位置填写需要填写的内容