Golang 模板顺序

Ada*_*ver 0 go go-templates

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

这是我的代码:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

var overallTemplates = []string{
    "templates/header.html",
    "templates/footer.html",
    "templates/analytics.html"}
Run Code Online (Sandbox Code Playgroud)

我得到了一个空白页面,因为analytics.html内容是一样的东西{{define "analytics"}}...{{end}}和它是由被称为footer.html{{define "footer"}}{{template "analytics"}} ...{{end}}

icz*_*cza 5

template.ParseFiles() 文件:

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

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

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

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

err := tmpl.ExecuteTemplate(w, "analytics", data)
Run Code Online (Sandbox Code Playgroud)

这样,您将模板传递给template.ParseFiles().

友情提示:不要在处理程序中解析模板:它很慢。在应用程序启动时解析它们,将它们存储在例如包变量中,然后在处理程序中执行它们。详情请参见Golang中使用“模板”包生成动态网页给客户端的时间过长

另请参阅相关问题:Go 模板名称