如何在高浪中正确筑巢?

在此代码中,我创建了一个文件来停止每个文件中代码的重复。我在 和 中都正确使用了 和 。base.htmlHTML{{define ".."}}{{template ".." .}}home.htmlabout.html


但是当我运行代码并访问 或 时,它只给出文件的结果。尽管对于链接,它应该给出文件的结果。localhost:8080localhost:8080/abouthome.html/aboutabout.html


主要.go


func main() {

    http.HandleFunc("/", handler.Home)

    http.HandleFunc("/about", handler.About)

    fmt.Println("Starting the server at :8080")

    http.ListenAndServe(":8080", nil)

}

处理程序.go


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


守候你守候我
浏览 129回答 1
1回答

哔哔one

使用时必须单独创建模板,对于每个页面,包括基.html和页面.html:var tmpl = make(map[string]*template.Template)func init() {&nbsp; &nbsp; tmpl["home"] = template.Must(template.ParseFiles("templates/home.html", "templates/base.html"))&nbsp; &nbsp; tmpl["about"] = template.Must(template.ParseFiles("templates/about.html", "templates/base.html"))}func Home(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; tmpl["home"].ExecuteTemplate(w, "home.html", nil)}func About(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; tmpl["about"].ExecuteTemplate(w, "about.html", nil)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go