var tpl *template.Template
func init() {
tpl = template.Must(template.ParseGlob("C:\\Users\\cat\\go\\src\\awesomeProject\\ch05_web\\public\\templates\\*.gohtml"))
}
- 初始化变量tpl,类型是 *template.Template。
-Init函数,执行Must函数和ParseGlob,执行载入模式,将模板已语法糖的形式载入。
-到此为止,tpl已经成为了一个 HTML document fragment.一个文档片段接口。
func main() {
http.HandleFunc("/", idx)
http.HandleFunc("/about", abt)
http.HandleFunc("/contact", cntct)
http.HandleFunc("/apply", aply)
http.Handle("/favicon.ico",http.NotFoundHandler())
http.ListenAndServe(":8080", nil)
}
-服务器main函数代码
func idx(w http.ResponseWriter, r *http.Request) {
pd := pageData{
Title:"主页",
}
err := tpl.ExecuteTemplate(w, "index.gohtml", pd)
if err != nil {
log.Println("LOGGER",err)
http.Error(w,"Internal Server Error",http.StatusInternalServerError)
return
}
fmt.Println(r.URL.Path)
fmt.Println("we got here")
}
- 初始化pageData,将html中的Title字段设定为主页
- 将之前初始化的tpl使用ExecuteTemplate方法加载模板
// ExecuteTemplate applies the template associated with t that has the given
// name to the specified data object and writes the output to wr.
// If an error occurs executing the template or writing its output,
// execution stops, but partial results may already have been written to
// the output writer.
// A template may be executed safely in parallel, although if parallel
// executions share a Writer the output may be interleaved.
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
tmpl, err := t.lookupAndEscapeTemplate(name)
if err != nil {
return err
}
return tmpl.text.Execute(wr, data)
}
一下几个处理器函数和Idx处理器是相同的,因此只放出代码不做执行。
func abt(w http.ResponseWriter, r *http.Request) {
pd := pageData{
Title:"关于s",
}
err := tpl.ExecuteTemplate(w, "about.gohtml", pd)
if err != nil {
log.Println(err)
http.Error(w,"Internal Server Error",http.StatusInternalServerError)
return
}
fmt.Println(r.URL.Path)
fmt.Println("we got here")
}
func cntct(w http.ResponseWriter, r *http.Request) {
pd := pageData{
Title:"联系我",
}
err := tpl.ExecuteTemplate(w, "contact.gohtml", pd)
if err != nil {
log.Println(err)
http.Error(w,"Internal Server Error",http.StatusInternalServerError)
return
}
fmt.Println(r.URL.Path)
fmt.Println("we got here")
}
func aply(w http.ResponseWriter, r *http.Request) {
var first string
pd := pageData{
Title:"提交",
}
if r.Method == "POST" {
first = r.FormValue("fname")
pd.FirstName = first
}
err := tpl.ExecuteTemplate(w, "apply.gohtml",pd)
if err != nil {
log.Println(err)
http.Error(w,"Internal Server Error",http.StatusInternalServerError)
return
}
fmt.Println(r.URL.Path)
fmt.Println("we got here")
}
最后一个处理器aply中,有一个新的string变量first。如果处理器收到一个"POST",那么就将form提供的变量fname传递给first。并将pageData的FirstName赋值。最后将得到的pd重新使用模板引擎加载到html文件中去。
模板
about.gohtml
{{template "header" .}}
<h1>关于</h1>
{{template "nav-main"}}
{{template "footer"}}
apply.gohtml
{{template "header" .}}
<h1>提交</h1>
{{template "nav-main"}}
{{if .FirstName}}
你的名字是 {{.FirstName }}
{{end}}
<form action="/apply" method="post">
<label for="fnm">姓名</label>
<input type="text" name="fname" id="fnm">
<input type="submit">
</form>
{{template "footer"}}
contact.gohtml
{{template "header" .}}
<h1>联系我</h1>
{{template "nav-main"}}
{{template "footer"}}
includes-hdr-ftr.gohtml
{{define "header"}}
<html lang="en">
<head>
<meta charset="UTF-8">
{{if .FirstName}}
<title>{{.FirstName}}</title>
{{else}}
<title>{{.Title}}</title>
{{end}}
</head>
<body>
<link rel="stylesheet" href="/public/css/main.css">
{{end}}
{{define "footer"}}
</body>
</html>
{{end}}
include-nav-main.gohtml
{{define "nav-main"}}
<nav>
<ul>
<li><a href="/index">主页</a> </li>
<Li><a href="/about">关于我</a> </Li>
<li><a href="/contact">联系我</a> </li>
<li><a href="/apply">提交</a> </li>
</ul>
</nav>
{{end}}
index.gohtml
{{template "header".}}
<h1>主页</h1>
{{template "nav-main"}}
<form action="/apply" method="post">
<input type="text" name="fname">
<input type="submit" name="fname" id="fnm">
</form>
{{template "footer"}}
有疑问加站长微信联系(非本文作者)