如何在Go中使用多个html模板即具有基本模板或页脚模板?

问题描述

我是Go的新手,正在使用Go设计一个网站。我希望使用多个模板(例如基本模板)与其他模板(例如索引)合并。我想在应用程序首次启动时进行所有模板解析。目前,我有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

感谢您的帮助。谢谢。

解决方法

html/template可以解决您的问题。您可以使用如下模板:

main.html

{{define "main"}}
<!DOCTYPE html>
<html lang="en">
<body>
{{template "header" .}}

{{template "content" .}}

{{template "footer" .}}
</body>
</html>
{{end}}

header.html

{{define "header"}}
// some header codes or menu or etc.
{{end}}

footer.html

{{define "footer"}}
// some header codes or menu or etc.
{{end}}

要复制index页面,您可以这样操作:

tmpl,err := template.New("").ParseFiles("index.html","main.html")
if err != nil {
    panic(err.Error())
}
err = tmpl.ExecuteTemplate(w,"main",whateverContext)