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

Mary-Kate Olsen
Release: 2024-11-10 09:38:02
Original
173 people have browsed it

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>
Copy after login

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

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}}
Copy after login

page1.html:

{{define "content"}}
I'm page 1
{{end}}
Copy after login

page2.html:

{{define "content"}}
I'm page 2
{{end}}
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template