Home > Backend Development > Golang > How can Base Layout Templates be Effectively Used with Go HTML/Template?

How can Base Layout Templates be Effectively Used with Go HTML/Template?

Barbara Streisand
Release: 2024-11-08 17:58:02
Original
300 people have browsed it

How can Base Layout Templates be Effectively Used with Go HTML/Template?

Using Base Layout Templates in Go HTML/Template

In the provided code, the issue lies in the improper usage of base template files. To resolve this, we need to define a base template file and reference it in our partial templates, which will be executed dynamically.

Base Template (base.html):

This file defines the overall layout of the page, including elements shared across all pages, such as header, footer, and navigation.

{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<body>
  <!-- Header -->

  {{template "content" .}}

  <!-- Footer -->
</body>
</html>
{{end}}
Copy after login

Partial Template 1 (page1.html):

This file defines the content specific to page 1.

{{define "content"}}
<h1>Page 1</h1>
{{end}}
{{template "base"}}
Copy after login

Partial Template 2 (page2.html):

This file defines the content specific to page 2.

{{define "content"}}
<h1>Page 2</h1>
{{end}}
{{template "base"}}
Copy after login

Usage:

To use the base template, parse the files containing the base and content templates:

tmpl, err := template.ParseFiles("page1.html", "base.html")
if err != nil {
    // Handle error
}
Copy after login

Then, execute the template with a specified content:

err = tmpl.ExecuteTemplate(w, "base", yourContext)
if err != nil {
    // Handle error
}
Copy after login

This will render the appropriate content within the base template layout.

The above is the detailed content of How can Base Layout Templates be Effectively Used with Go HTML/Template?. 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