Is it possible to have nested templates in Go using the standard library?

前端 未结 5 1721
时光说笑
时光说笑 2020-12-12 09:30

How do I get nested templates like Jinja has in the python runtime. TBC what I mean is how do I have a bunch of templates inherit from a base templates, just filing in block

5条回答
  •  情深已故
    2020-12-12 10:08

    note, when you execute your base template, you must pass values down to the child templates, here I simply pass ".", so that everything is passed down.

    template one displays {{.}}

    {{define "base"}}
    
            
    {{.}} {{template "content" .}}
    {{end}}

    template two displays {{.domains}} that's passed into the parent.

    {{define "content"}}
    {{.domains}}
    {{end}}
    

    Note, if we used {{template "content" .}} instead of {{template "content" .}}, .domains wouldn't be accessible from the content template.

    DomainsData := make(map[string]interface{})
        DomainsData["domains"] = domains.Domains
        if err := groupsTemplate.ExecuteTemplate(w, "base", DomainsData); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }
    

提交回复
热议问题