基础模板
block
关键字允许您定义页面一个或多个主模板的外壳,然后根据需要填充或覆盖部分。
基础模板查找顺序
基础模板查找顺序与其应用的模板(例如 _default/list.html
)的查找顺序非常相似。
有关详细信息和示例,请参阅模板查找顺序。
定义基础模板
以下定义了一个简单的基础模板,位于 _default/baseof.html
。作为默认模板,它是呈现所有页面的外壳,除非您在查找顺序的开头指定另一个更接近的 *baseof.html
。
layouts/_default/baseof.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ block "title" . }}
<!-- Blocks may include default content. -->
{{ .Site.Title }}
{{ end }}</title>
</head>
<body>
<!-- Code that all your templates share, like a header -->
{{ block "main" . }}
<!-- The part of the page that begins to differ between templates -->
{{ end }}
{{ block "footer" . }}
<!-- More shared code, perhaps a footer but that can be overridden if need be in -->
{{ end }}
</body>
</html>
覆盖基础模板
默认列表模板将继承上面定义的所有代码,然后可以从以下位置实现自己的 "main"
块
layouts/_default/list.html
{{ define "main" }}
<h1>Posts</h1>
{{ range .Pages }}
<article>
<h2>{{ .Title }}</h2>
{{ .Content }}
</article>
{{ end }}
{{ end }}
这会将我们(基本上为空)的 “main” 块的内容替换为对列表模板有用的内容。在这种情况下,我们没有定义 "title"
块,因此基础模板中的内容在列表中保持不变。
以下显示了如何使用对您的默认单页模板唯一的内容覆盖基础模板中的 "main"
和 "title"
块区域
layouts/_default/single.html
{{ define "title" }}
<!-- This will override the default value set in baseof.html; i.e., "{{ .Site.Title }}" in the original example-->
{{ .Title }} – {{ .Site.Title }}
{{ end }}
{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ .Content }}
{{ end }}