【问题标题】:How to do nesting in golang correctly? [duplicate]如何正确地在 golang 中进行嵌套? [复制]
【发布时间】:2021-10-14 15:58:21
【问题描述】:

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

但是当我运行代码并访问localhost:8080localhost:8080/about 时,它只给出home.html 文件的结果。虽然对于/about 链接,它应该给出about.html 文件的结果。

ma​​in.go

func main() {
    http.HandleFunc("/", handler.Home)
    http.HandleFunc("/about", handler.About)
    fmt.Println("Starting the server at :8080")
    http.ListenAndServe(":8080", nil)
}

handler.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)
}

base.html

{{define "base"}}

<!DOCTYPE html>
<html lang="en">
<head>
    <title>{{template "title" .}}</title>
</head>
<body>
    <section>
        {{template "body" .}}
    </section>
</body>
</html>

{{end}}

home.html

{{template "base" .}}

{{define "title"}} Home page {{end}}

{{define "body"}} 
    <h1>Home page</h1>
    <p>This is the home page</p>
{{end}}

about.html

{{template "base" .}}

{{define "title"}} About page {{end}}

{{define "body"}} 
    <h1>About page</h1>
    <p>This is an about page</p>
{{end}}

【问题讨论】:

标签: html go templates


【解决方案1】:

使用必须单独创建模板,每个页面包括base.html和page.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)
}

【讨论】:

  • 我实现了代码,但是没有加载任何页面。
  • @sikandarmeranam 你能分享你更新的代码吗(创建 github gist 或类似的)?
  • 我在main.go 中编写了所有函数并删除了handler.go 中的函数并且它有效但是当我在handler.go 中编写函数并在主函数中调用它们时,它没有工作。虽然我把这些函数称为handler.Home
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-23
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
  • 2011-07-18
  • 2020-06-18
  • 1970-01-01
相关资源
最近更新 更多