Home  >  Article  >  Backend Development  >  How can I implement Base Templates in Go's HTML/Template package?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 09:38:02197browse

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):

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

header...

{{template "content" .}}

footer...

</body>
</html>

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

{{define "content"}}
<div>
    <h1>Page1</h1>
</div>
{{end}}
{{template "base.html"}}
{{define "content"}}
<div>
    <h1>Page2</h1>
</div>
{{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"}}
<!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}}

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)

The above is the detailed content of How can I implement Base Templates in Go's HTML/Template package?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn