gogo-templates

How to use base template file for golang html/template?


Have gin-gonic web app.

There are 3 files:

1) base.html -- base layout file

<!DOCTYPE html>
<html lang="en">
<body>

header...

{{template "content" .}}

footer...

</body>
</html>

2) page1.html, for /page1

{{define "content"}}
<div>
    <h1>Page1</h1>
</div>
{{end}}
{{template "base.html"}}

3) page2.html, for /page2

{{define "content"}}
<div>
    <h1>Page2</h1>
</div>
{{end}}
{{template "base.html"}}

The problem is that /page1 and /page2 use one template - page2.html. I think that I have misunderstanding of such constructions: {{define "content"}}, {{template "base.html"}}.

Please, can you show an example how to use base layouts in golang?


Solution

  • You can use the base.html as long as you parse the template along with your "content", like so:

    base.html

    {{define "base"}}
    <!DOCTYPE html>
    <html lang="en">
    <body>
    
    header...
    
    {{template "content" .}}
    
    footer...
    
    </body>
    </html>
    {{end}}
    

    page1.html

    {{define "content"}}
    I'm page 1
    {{end}}
    

    page2.html

    {{define "content"}}
    I'm page 2
    {{end}}
    

    then ParseFiles with ("your-page.html", "base.html"), and ExecuteTemplate with your context.

    tmpl, err := template.New("").ParseFiles("page1.html", "base.html")
    // check your err
    err = tmpl.ExecuteTemplate(w, "base", yourContext)