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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分