duanaoshu1989 2019-08-03 15:27
浏览 57
已采纳

Golang模板顺序

Is there a way to make the template order irrelevant.

Here's my code:

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
", err)
    }
}

It works but if I change the order of overallTemplates to:

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

I get a blank page because analytics.html content is something like {{define "analytics"}}...{{end}} and it's called by footer.html like {{define "footer"}}{{template "analytics"}} ...{{end}}

  • 写回答

1条回答 默认 最新

  • duannei1477 2019-08-03 16:16
    关注

    template.ParseFiles() documents that:

    The returned template's name will have the (base) name and (parsed) contents of the first file.

    So in your first example your template designates "templates/analytics.html" because that's the first template you pass, and when you change order, the template will designate "templates/header.html".

    And if you execute the template with Template.Execute(), these are the (default) templates to be executed.

    Instead you should use Template.ExecuteTemplate() and explicitly specify you want to execute the "templates/analytics.html", whose name will be analytics, so pass that:

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

    That way it will not matter in what order you pass the templates to template.ParseFiles().

    And a friendly note: do not parse your templates in the handler: it's slow. Parse them once, on app startup, store them e.g. in package variables, and just execute them in the handler. For details, see It takes too much time when using "template" package to generate a dynamic web page to client in Golang.

    Also see related quesetion: Go template name

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里