How Do I Use Base Template Files in Go's HTML/Template?

DDD
Release: 2024-11-07 11:12:03
Original
959 people have browsed it

How Do I Use Base Template Files in Go's HTML/Template?

Using Base Template Files in Go's HTML/Template

In web development, using base layout templates helps maintain consistency across multiple pages. Let's understand how to use this technique in Go's HTML/Template.

For example, let's say we have three files:

base.html: The base layout file

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

header...

{{template "content" .}}

footer...

</body>
</html>
Copy after login

page1.html: A page template for "/page1"

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

page2.html: A page template for "/page2"

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

The issue is that both "/page1" and "/page2" are currently using the same template file, "page2.html."

To use the "base.html" layout template, you need to parse both the "content" and "base" templates together. This is achieved using ParseFiles and ExecuteTemplate.

base.html (Updated):

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

header...

{{template "content" .}}

footer...

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

page1.html (Updated):

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

page2.html (Updated):

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

Usage:

tmpl, err := template.New("").ParseFiles("page1.html", "base.html")
// handle error
err = tmpl.ExecuteTemplate(w, "base", yourContext)
Copy after login

This will render the appropriate content within the base layout template. For instance, when rendering "/page1," the content "I'm page 1" will be incorporated into the base template's {{template "content. ."}} section.

The above is the detailed content of How Do I Use Base Template Files in Go's 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!