如何解决Gin Gonic 模板覆盖部分模板
我正在使用 gin gonic 和它的功能。一个如果它们是 html 模板渲染。
因此,本着 DRY 的精神,我想创建一个 base.html
模板,其中包含所有常见的 html 标签等。
用于不同页面主体的插槽。
本质上,这是base.html
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
{{ template "main" . }}
</body>
</html>
{{end}}
然后我创建了一个名为 home.html
的“子”模板:
{{template "base" .}}
{{define "main"}}
<div class="container mt-5">
Hello
</div>
{{end}}
我在 this page 上遵循了这个精彩的指南,它的作用就像一个魅力。
问题
但是当我尝试在 subpage.html
中添加另一个具有不同正文的页面时,例如:
{{template "base" .}}
{{define "main"}}
<div class="container">
<div>
<h2>This page is still in progress</h2>
</div>
</div>
{{end}}
由 gins LoadHTMLFiles
或 LoadHTMLGlob
选取的最后一个模板然后显示在每一页上。在这种情况下,这是 subpage.html
内容。
我该如何解决。默认情况下甚至可以实现这种行为吗?
解决方法
你可以这样做:
base.html
{{ define "top" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
{{ end }}
{{ define "bottom" }}
</body>
</html>
{{ end }}
home.html
{{ template "top" . }}
<div class="container mt-5">
Hello
</div>
{{ template "bottom" . }}
subpage.html
{{ template "top" . }}
<div class="container">
<div>
<h2>This page is still in progress</h2>
</div>
</div>
{{ template "bottom" . }}
然后确保您使用的是文件的基本名称:
// in the home handler use the following
c.HTML(http.StatusOK,"home.html",data)
// in the subpage handler use the following
c.HTML(http.StatusOK,"subpage.html",data)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。