Home > Backend Development > Golang > How do Base Templates Work in Golang HTML/Template?

How do Base Templates Work in Golang HTML/Template?

DDD
Release: 2024-11-08 11:00:02
Original
474 people have browsed it

How do Base Templates Work in Golang HTML/Template?

Utilizing Base Templates in Golang HTML/Template

In your given scenario, you're facing a misunderstanding regarding the usage of base templates. The problem lies in your belief that pages 1 and 2 are using the same template when in reality, they are referencing the same base template and defining unique content sections.

Canonical Usage of Base Templates

To use base templates effectively, follow these steps:

  1. Define Multiple Templates: Create one base template (e.g., base.html) containing the common layout of your site. Define specific content sections within this base template using {{define "content"}}.
  2. Create Content Templates: For each unique page on your site, create separate templates (e.g., page1.html, page2.html). Within these templates, define the content to be displayed within the "content" section of the base template using {{define "content"}}.
  3. Include Base Template: In each content template, instruct the template engine to include the base template using {{template "base.html"}}. This ensures that the base layout is used as the framework for each page.

Example Implementation

Below is an example implementation based on your provided code:

base.html

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

header...

{{template "content" .}}

footer...

</body>
</html>
{{end}}
Copy after login

page1.html

{{define "content"}}
<div>
  <h1>Page1</h1>
</div>
{{end}}
{{template "base.html"}}
Copy after login

page2.html

{{define "content"}}
<div>
  <h1>Page2</h1>
</div>
{{end}}
{{template "base.html"}}
Copy after login

Template Parsing and Execution
Once your templates are defined, you can parse them using template.New("").ParseFiles(page1.html, base.html)) and execute them with tmpl.ExecuteTemplate(w, "base", yourContext).

The above is the detailed content of How do Base Templates Work in Golang 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template