Ari
Ari

Reputation: 6209

How to extend a base template to other templates

How do I extend a base html file, such as:

base.html

<!DOCTYPE html>
    <html>
    <head>
        <title>My Site</title>
    </head>
    <body>
   <!-- insert html here -->
    </body>
    </html>

And then create a page that inherits that base template, in Python Jinja2 I would do:

main.html

{{ extend "base.html" }}

main.html now has all the HTML from base.html. Then so long as I defined an area in my base.html file to insert html into I could do it from main.html, in Jinja2 it would look like:

base.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>My Site</title>
    </head>
    <body>
   {{ block "body" }}

   {{ endblock }}
    </body>
    </html>

then in main.html

{{ extend "base.html" }}
{{ block "body" }}
<h1>Title</h1>
{{ endblock }}

I can't figure the way to do that in any of the Go frameworks. They all seem to say to 'define' a template and then insert HTML "components" into it, I want to go the other way and define a base HTML file and inherit it into my other HTML files to build upon, if that makes sense?

Upvotes: 0

Views: 1232

Answers (1)

Thundercat
Thundercat

Reputation: 121199

Use these templates.

base.html:

<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
</head>
<body>
{{block "body" $}}{{end}}
</body>
</html>`

main.html:

{{define "body"}}<h1>Title</h1>{{end}}

Parse the templates in order of extension using the standard library template package;

t := template.Must(template.ParseFiles(
     "base.html", 
     "main.html"))

Execute the resulting template.

Run it on the playground

Upvotes: 5

Related Questions