去模板扩展和超级?

In Flask, we can extend from base.html in template. How do I extend or super() using Go's standard template library? Otherwise, in case that I need to use top bar, I would have to manually copy and paste code for top bar. Please let me know.

In Go, You can using html/template

Then you can define header, body, and footer look like

// header.tpl:
{{define "header"}}
<html>
<head></head>
{{end}}

// body.tpl:
{{template "header" .}}
{{define "body"}}
<body>
</body>
{{end}}
{{template "footer" .}}

// footer.tpl:
{{define "footer"}}
</html>
{{end}}

s1, _ := template.ParseFiles("header.tpl", "body.tpl", "footer.tpl") //create a set of templates from many files.
s1.Execute(os.Stdout, nil)

Reference: http://golangtutorials.blogspot.com/2011/11/go-templates-part-3-template-sets.html

The jist of it is that you would have some parent template (we'll call it layout) that is executed as the initial template, and inside that layout parent template is something like {{template "someName" .}}.

See: https://github.com/jadekler/git-go-websiteskeleton/blob/master/templates/layout.html#L40. That repo is a very lightweight skeleton with basic go packages - you may find some value in checking it out.

I ran into this issue with templates. I've used a variety of templating engines before that support inheritance.

To get round the limitation I've actually copied the standard text/template package to removing the redefinition error (from template.go) and test (from multi_test.go). This allows you to redefine templates/define blocks in templates.

I created a github repo https://github.com/d2g/goti which contains examples etc. There are loads of things I still need to do on the repo (Tag Versions etc) [Hint Pull requests welcome].

If you're searching for a jinja2/Django-like template language for Go (which supports both template inheritance and template inclusion like mentioned before), you should give pongo2 a try.

One solution I found was to refer everything to my base.gohtml and then use logic to determine what template should be included.

func dashboard(w http.ResponseWriter, req *http.Request) {
    data := struct {
        Page string
    }{
        "dashboard",
    }
    err := tpl.ExecuteTemplate(w, "base", data)
    if err != nil {
        log.Fatalln(err)
    }
}

and then inside my base template:

headers, navs, css
{{if eq .Page "dashboard"}}
    {{template "dashboard"}}
{{else if .Page "login"}}
    {{template "login"}}
{{else}}
    ...
{{end}}
footers, scripts