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 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等