我正在使用 Golang 模板构建一个网站,并且需要在页脚模板中显示一些文本。它是一个在 header.html 和 index.html 中解析的变量。
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
type Data struct {
Title string
Field1 string
Field2 template.HTML
FooterField string
}
var tmpl *template.Template
func main() {
router := mux.NewRouter()
port := ":8085"
data := Data{}
data.Title = "Title"
data.FooterField = "This text does not appear in the footer template"
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
err := tmpl.ExecuteTemplate(w, "index", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
var err error
tmpl, err = template.ParseGlob("views/*")
if err != nil {
panic(err.Error())
}
router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)
})
fmt.Println("Server running on localhost" + port)
err = http.ListenAndServe(port, handlers.CompressHandler(router))
if err != nil {
log.Fatal(err)
}
}
在 ./views 我有 header.html
{{define "header"}}<!doctype html><html><head><meta charset="utf-8"><title>{{.Title}}</title></head><body><h1>Header template</h1><div>{{.FooterField}}</div>{{end}}
索引.html
{{define "index"}}{{template "header" . }}
<h1>Index template</h1>
<div>{{.FooterField}}</div>
{{template "footer"}}{{end}}
页脚.html
{{define "footer"}}<h1>Footer template</h1>
Missing FooterField->{{.FooterField}}</body></html>{{end}}
最后在浏览器中输出 http://localhost:8085/
Header template
This text does not appear in the footer template
Index template
This text does not appear in the footer template
Footer template
Missing FooterField->
只需复制和粘贴即可复制此代码。
任何线索我的问题是什么?
手掌心
相关分类