Home >Backend Development >Golang >How do Base Templates Work in Golang HTML/Template?
Utilizing Base Templates in Golang HTML/Template
In your given scenario, you're facing a misunderstanding regarding the usage of base templates. The problem lies in your belief that pages 1 and 2 are using the same template when in reality, they are referencing the same base template and defining unique content sections.
Canonical Usage of Base Templates
To use base templates effectively, follow these steps:
Example Implementation
Below is an example implementation based on your provided code:
base.html
{{define "base"}} <!DOCTYPE html> <html lang="en"> <body> header... {{template "content" .}} footer... </body> </html> {{end}}
page1.html
{{define "content"}} <div> <h1>Page1</h1> </div> {{end}} {{template "base.html"}}
page2.html
{{define "content"}} <div> <h1>Page2</h1> </div> {{end}} {{template "base.html"}}
Template Parsing and Execution
Once your templates are defined, you can parse them using template.New("").ParseFiles(page1.html, base.html)) and execute them with tmpl.ExecuteTemplate(w, "base", yourContext).
The above is the detailed content of How do Base Templates Work in Golang HTML/Template?. For more information, please follow other related articles on the PHP Chinese website!