【问题标题】:Golang template orderGolang 模板顺序
【发布时间】:2019-08-03 15:27:17
【问题描述】:

有没有办法让模板顺序无关紧要。

这是我的代码:

var overallTemplates = []string{
    "templates/analytics.html",
    "templates/header.html",
    "templates/footer.html"}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    render(w,
        append([]string{"templates/home.html"}, overallTemplates...),
        nil)
}

func render(w http.ResponseWriter, files []string, data interface{}) {
    tmpl := template.Must(template.ParseFiles(files...))
    err := tmpl.Execute(w, data)

    if err != nil {
        fmt.Printf("Couldn't load template: %v\n", err)
    }
}

它有效,但如果我将overallTemplates 的顺序更改为:

var overallTemplates = []string{
    "templates/header.html",
    "templates/footer.html",
    "templates/analytics.html"}

我得到一个空白页,因为 analytics.html 内容类似于 {{define "analytics"}}...{{end}},它由 footer.html 调用,例如 {{define "footer"}}{{template "analytics"}} ...{{end}}

【问题讨论】:

  • 顺序已经或多或少无关紧要,重要的是您执行了哪个模板

标签: go go-templates


【解决方案1】:

template.ParseFiles() 文件表明:

返回的模板名称将包含第一个文件的(基本)名称和(解析的)内容。

因此,在您的第一个示例中,您的模板指定 "templates/analytics.html",因为这是您传递的第一个模板,当您更改顺序时,模板将指定 "templates/header.html"

如果您使用Template.Execute() 执行模板,这些是要执行的(默认)模板。

相反,您应该使用Template.ExecuteTemplate() 并明确指定您要执行"templates/analytics.html",其名称将为analytics,因此传递:

err := tmpl.ExecuteTemplate(w, "analytics", data)

这样,您将模板传递给template.ParseFiles() 的顺序无关紧要。

还有一个友好的提示:不要在处理程序中解析您的模板:它很慢。在应用程序启动时解析它们一次,存储它们,例如在包变量中,只需在处理程序中执行它们。详情请见It takes too much time when using "template" package to generate a dynamic web page to client in Golang

另见相关问题:Go template name

【讨论】:

  • 我是 Go 新手,非常感谢您的补充说明 - 非常有帮助。
猜你喜欢
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多