【问题标题】:How can I use multiple html templates (ie. have a base template or footer template) in Go?如何在 Go 中使用多个 html 模板(即有一个基本模板或页脚模板)?
【发布时间】: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


    【解决方案1】:

    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}}
    
    

    页脚.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)
    

    【讨论】:

    • 感谢您抽出宝贵时间回复@ttrasn。当我今天下午/晚上晚些时候有机会时,我一定会尝试一下并在这里更新我的结果。从您的回答看来,我每次使用模板时都必须解析模板,对吗?我基本上是在遵循一个教程(golang.org/doc/articles/wiki),其中只需在应用程序启动时解析所有模板一次,然后在需要时执行模板,但如果解析每个请求是正确的解决方案,那就这样吧。再次感谢。
    猜你喜欢
    • 2020-09-22
    • 2015-01-14
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多