"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I implement Base Templates in Go's HTML/Template package?

How can I implement Base Templates in Go's HTML/Template package?

Published on 2024-11-20
Browse:794

How can I implement Base Templates in Go's HTML/Template package?

Implementing Base Templates in Go's HTML/Template

When working with complex layouts in web applications, it's often useful to create a base template that serves as a foundation for other pages. In Go's html/template package, this can be achieved using {{define}} and {{template}} directives.

Consider the following example where you have a base layout file (base.html):




header...

{{template "content" .}}

footer...


And separate pages (page1.html and page2.html) that reuse this base layout with their own custom content:

{{define "content"}}

Page1

{{end}} {{template "base.html"}}
{{define "content"}}

Page2

{{end}} {{template "base.html"}}

The issue you're encountering is that both page 1 and page 2 are using the same HTML for rendering, which is defined in page2.html. To address this, we need to make sure that both pages declare and use their own unique content sections within the {{template}} block.

A better approach is to define the template content in separate files, as shown below:

base.html:

{{define "base"}}




header...

{{template "content" .}}

footer...



{{end}}

page1.html:

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

page2.html:

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

In your application, you can then parse the content and base template files into a template object using template.New() and ParseFiles(). Subsequently, you can build the final HTML by executing the base template with your desired context using ExecuteTemplate().

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

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3