【问题标题】:Gin gonic templates overwriting partial templatesGin Gonic 模板覆盖部分模板
【发布时间】:2021-03-20 16:38:04
【问题描述】:

我正在使用 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 LoadHTMLFilesLoadHTMLGlob 选择的最后一个模板会显示在每一页上。在这种情况下,这是subpage.html 内容。 我该如何解决。甚至可以默认实现这种行为吗?

【问题讨论】:

  • 首先想到的你可以做的就是将基础分成两个顶部/底部或页眉/页脚,然后你的每个主干都会在顶部调用顶部,在底部调用底部,如果您想避免最初的问题,您的每个主电源都应该有一个唯一的名称,实际上您可以完全删除“主”名称,并确保每个处理程序使用模板文件的唯一基本名称呈现其相应的模板。
  • 嗯,这是一种方法。但是想象一下有很多这样的子页面。我觉得效率很低。我来自 django 环境,它已经具有模板继承的这些功能。
  • 什么是低效?这实际上将每个模板的代码版本减少了一行。也许您误解了我的建议,或者我误解了您的要求。我将通过示例提供答案以更清楚地说明我的意思,然后您可以评论为什么这对您来说不是一个好的解决方案。
  • 请注意,您可以使您的初始模板设计工作,Go 支持。基本上不是使用像 LoadHTMLFiles/LoadHTMLGlob 这样的东西来解析所有文件并依赖于它们名称的唯一性来知道你想要呈现哪个文件,你会解析每个特定于页面的模板文件及其依赖项,但是与其他特定于页面的模板文件分开,这样您最终每个页面处理程序都有一个 *template.Template 对象,然后您从其相应的处理程序执行该模板对象。

标签: html go go-gin


【解决方案1】:

你可以这样做:

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)

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2019-03-27
    • 2020-02-18
    • 1970-01-01
    相关资源
    最近更新 更多