为了账号安全,请及时绑定邮箱和手机立即绑定

如何在高浪中正确筑巢?

如何在高浪中正确筑巢?

Go
守候你守候我 2022-09-19 17:40:50
在此代码中,我创建了一个文件来停止每个文件中代码的重复。我在 和 中都正确使用了 和 。base.htmlHTML{{define ".."}}{{template ".." .}}home.htmlabout.html但是当我运行代码并访问 或 时,它只给出文件的结果。尽管对于链接,它应该给出文件的结果。localhost:8080localhost:8080/abouthome.html/aboutabout.html主要.gofunc main() {    http.HandleFunc("/", handler.Home)    http.HandleFunc("/about", handler.About)    fmt.Println("Starting the server at :8080")    http.ListenAndServe(":8080", nil)}处理程序.gofunc init() {    tmpl = template.Must(template.ParseGlob("templates/*.html"))}func Home(w http.ResponseWriter, r *http.Request) {    tmpl.ExecuteTemplate(w, "home.html", nil)}func About(w http.ResponseWriter, r *http.Request) {    tmpl.ExecuteTemplate(w, "about.html", nil)}基地.html{{define "base"}}<!DOCTYPE html><html><head>    <title>{{template "title" .}}</title></head><body>    <section>        {{template "body" .}}    </section></body></html>{{end}}家.html{{template "base" .}}{{define "title"}} Home page {{end}}{{define "body"}}     <h1>Home page</h1>    <p>This is the home page</p>{{end}}关于.html{{template "base" .}}{{define "title"}} About page {{end}}{{define "body"}}     <h1>About page</h1>    <p>This is an about page</p>{{end}}
查看完整描述

1 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

使用时必须单独创建模板,对于每个页面,包括基.html和页面.html:


var tmpl = make(map[string]*template.Template)


func init() {

    tmpl["home"] = template.Must(template.ParseFiles("templates/home.html", "templates/base.html"))

    tmpl["about"] = template.Must(template.ParseFiles("templates/about.html", "templates/base.html"))

}


func Home(w http.ResponseWriter, r *http.Request) {

    tmpl["home"].ExecuteTemplate(w, "home.html", nil)

}


func About(w http.ResponseWriter, r *http.Request) {

    tmpl["about"].ExecuteTemplate(w, "about.html", nil)

}


查看完整回答
反对 回复 2022-09-19
  • 1 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号