Home >Backend Development >Golang >How Do I Use Base Template Files in Go's HTML/Template?
Using Base Template Files in Go's HTML/Template
In web development, using base layout templates helps maintain consistency across multiple pages. Let's understand how to use this technique in Go's HTML/Template.
For example, let's say we have three files:
base.html: The base layout file
<!DOCTYPE html> <html lang="en"> <body> header... {{template "content" .}} footer... </body> </html>
page1.html: A page template for "/page1"
{{define "content"}} <div> <h1>Page1</h1> </div> {{end}} {{template "base.html"}}
page2.html: A page template for "/page2"
{{define "content"}} <div> <h1>Page2</h1> </div> {{end}} {{template "base.html"}}
The issue is that both "/page1" and "/page2" are currently using the same template file, "page2.html."
To use the "base.html" layout template, you need to parse both the "content" and "base" templates together. This is achieved using ParseFiles and ExecuteTemplate.
base.html (Updated):
{{define "base"}} <!DOCTYPE html> <html lang="en"> <body> header... {{template "content" .}} footer... </body> </html> {{end}}
page1.html (Updated):
{{define "content"}} I'm page 1 {{end}}
page2.html (Updated):
{{define "content"}} I'm page 2 {{end}}
Usage:
tmpl, err := template.New("").ParseFiles("page1.html", "base.html") // handle error err = tmpl.ExecuteTemplate(w, "base", yourContext)
This will render the appropriate content within the base layout template. For instance, when rendering "/page1," the content "I'm page 1" will be incorporated into the base template's {{template "content. ."}} section.
The above is the detailed content of How Do I Use Base Template Files in Go's HTML/Template?. For more information, please follow other related articles on the PHP Chinese website!