Hugo模板功能及加载顺序说明

Hugo的模板结构并不复杂,常用的无非首页、404页、分类页、标签页和文章页。

Hugo的所有模板文件位于主题目录中的layouts目录里,大致结构如下:

├── _default
│   ├── baseof.html
│   ├── list.html
│   └── single.html
├── partials
│   ├── header.html
│   ├── footer.html
└── index.html
└── 404.html

_default目录存放各种页面模板,partials目录中存放自定义的一些片段模板。

模板加载顺序

首页模板:

  1. /index.html
  2. /home.html
  3. /list.html
  4. /_default/index.html
  5. /_default/home.html
  6. /_default/list.html

首页基础模板加载顺序:

  1. /index-baseof.html
  2. /home-baseof.html
  3. /list-baseof.html
  4. /baseof.html
  5. /_default/index-baseof.html
  6. /_default/home-baseof.html
  7. /_default/list-baseof.html
  8. /_default/baseof.html

文章页模板:

  1. /posts/single.zh.html
  2. /posts/single.html
  3. /_default/single.html

posts可以是其他自定义内容目录,例如pages,在Hugo中称为section。

文章页面的基础模板加载顺序:

  1. /posts/single-baseof.html
  2. /_default/baseof.html

分类法页面:

Hugo支持自定义分类法,常用的分类法包含category和tag。

  1. /categories/category.terms.html
  2. /categories/terms.html
  3. /categories/taxonomy.html
  4. /categories/list.html
  5. /category/category.terms.html
  6. /category/terms.html
  7. /category/taxonomy.html
  8. /category/list.html
  9. /taxonomy/category.terms.html
  10. /taxonomy/terms.html
  11. /taxonomy/taxonomy.html
  12. /taxonomy/list.html
  13. /_default/category.terms.html
  14. /_default/terms.html
  15. /_default/taxonomy.html
  16. /_default/list.html

Section页面:

所谓Section页面,是指content目录中的子目录页面。例如:在content目录创建一个posts目录,那么,访问以下路径即是Section页面:

https://www.beizigen.com/posts
  1. /posts/posts.html
  2. /posts/section.html
  3. /posts/list.html
  4. /section/posts.html
  5. /section/section.html
  6. /section/list.html
  7. /_default/posts.html
  8. /_default/section.html
  9. /_default/list.html

模板引用嵌套

通常网站的头部和页脚整站都是统一的,在其他模板可以使用以下代码嵌入:

{{ template "dirname/header.html" . }}

partials目录中会存放一些碎片模板,例如header.html和footer.html,引用方法如下:

{{ partial "header.html" . }}

注意以上代码不包含partials目录详细路径,只需要文件名即可。

baseof.html模板用来定义模板框架,如:

<!DOCTYPE html>
<html lang="{{ .Site.LanguageCode }}">
<head>
	<meta charset="UTF-8">
	<title>{{- .Title }} - {{ .Site.Title -}}</title>
</head>
<body>
{{- block "main" . -}}
{{- end -}}
</body>
</html>

这里需要关注的代码是:

{{- block "main" . -}}
{{- end -}}

在要使用baseof.html模板框架的模板中,例如single.html,代码示例如下:

{{ define "main" }}
<div class="content">
	{{ .Content }}
</div>
{{ end }}
阿里云