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
Barbara StreisandOriginal
2024-11-08 17:58:02297browse

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}}

Partial Template 1 (page1.html):

This file defines the content specific to page 1.

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

Partial Template 2 (page2.html):

This file defines the content specific to page 2.

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

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
}

Then, execute the template with a specified content:

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

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!

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