文章中的源码: https://github.com/Suroppo/hugo-theme-demo

首页也属于列表页, 只是他是一个特殊的列表页. 如果没有给首页添加模板, 首页使用内容页的模板.

DEMO的目录结构

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
├─content
│  ├─news
│  └─post
├─data
├─layouts
├─static
└─themes
    └─study-theme
        ├─archetypes
        ├─layouts
        │  ├─index.html
        │  ├─partials
        │  └─_default
        └─static

首页模板的位置

/themes/study-theme/layouts/index.html 首页模板使用单独的模板, 模板的名字也是固定的 index.html. 也可以给首页添加一个markdown文件, 位置在content根目录下, /content/_index.md. 这个不是必须的.

在首页中展示各章节的文章列表

首页是整个网站的一个索引, 我们一般会在首页中展示各个板块的文章列表, 在本DEMO中我们添加了两个板块, 也就是/content目录中的news 和 post这两个章节目录, 现在我们把这两个章节的内容添加到首页中.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>网站首页</title>
</head>

<body>
    <h2> 新闻列表 </h2>
    {{ range where .Site.RegularPages "Section" "news" }}
    <div>
        <a href="">{{.Title}}</a>
    </div>
    {{ end }}

    <h2> 博文列表 </h2>
    {{ range where .Site.RegularPages "Section" "post" }}
    <div>
        <a href="">{{.Title}}</a>
    </div>
    {{ end }}
</body>

</html>

这里主要用到两点

  • .Site.RegularPages 表示网站下面的所有节点内容, 具体到本例, 就是news和post目录下的所有文章
  • where 是一个函数, 用来查询集合中符合条件的项目.

where 的语法: where COLLECTION KEY [OPERATOR] MATCH

where .Site.RegularPages "Section" "news" 的含义就是, 查找出section属性的值为news的项目