【发布时间】:2020-12-06 03:27:43
【问题描述】:
我是 Go 新手,正在使用 Go 设计一个网站。我希望使用多个模板,例如一个基本模板来与其他模板合并,例如 index.html。我想在应用程序首次启动时解析所有模板。目前,我有 base.html、footer.html 和 index.html。我希望提供使用 base.html 和 footer.html 的 index.html。目前,我从服务器获得的唯一响应是由wireshark 验证的200 HTTP 响应中的一个换行符。无论如何,这是我的文件:
main.go
package main
import (
"html/template"
"log"
"net/http"
)
type Initial struct {
Data string
}
var cached_templates = template.Must(template.ParseFiles("templates/base.html",
"templates/footer.html",
"templates/index.html"))
func renderInitialTemplate(w http.ResponseWriter, _template string, data *Initial) {
err := cached_templates.ExecuteTemplate(w, _template, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
data := &Initial{Data: "Bob"}
renderInitialTemplate(w, "index.html", data)
}
func main() {
http.HandleFunc("/", indexHandler)
log.Fatal(http.ListenAndServe(":80", nil))
}
index.html - https://pastebin.com/LPy0Xb2Z
footer.html - https://pastebin.com/vVenX4qE
base.html - https://pastebin.com/1jKxv7Uz
感谢您的帮助。谢谢。
【问题讨论】:
标签: go go-html-template