需求

在页面底部增加相关阅读区域:

  • 简单实现与文章相同 tag 的文章列出到文章底部

实验步骤

layouts/partials/related.html 新创建一个模板,增加如下内容,本文主题为 PaperModX ,不同的主题,文件在不同目录下

html
1
2
3
4
5
6
7
8
9
{{ $related := .Site.RegularPages.Related . | first 3 }}
{{ with $related }}
<h3>Related Posts</h3>
<ul>
	{{ range . }}
	<li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li>
	{{ end }}
</ul>
{{ end }}

将模板加载到文章列表模板内

然后需要在文章列表页底部包含这个 “模板” _default/single.html 不同主题在不同的目录下

html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
...
  <!-- 分割线 -->
  <!-- Related -->
 <!-- 这个判断因为相关阅读增加了分割线,所以判断是指定页面就不在加载相关阅读和分割线了 -->
  {{ if and  (not (strings.Contains .RelPermalink "/tags")) (not (strings.Contains .RelPermalink "/posts")) (not (strings.Contains .RelPermalink "/archives")) (not (strings.Contains .RelPermalink "/search")) (not (strings.Contains .RelPermalink "/about")) }}
    <div class="comments-separator"></div>
    {{ partial "related.html" . }}
  {{- end }}
  <!-- /Related -->

  <!-- gittalk -->
  {{- if not (.Param "noComments") }}
    {{ if and  (not (strings.Contains .RelPermalink "/tags")) (not (strings.Contains .RelPermalink "/posts")) (not (strings.Contains .RelPermalink "/archives")) (not (strings.Contains .RelPermalink "/search")) (not (strings.Contains .RelPermalink "/about")) }}
      <div class="comments-separator"></div>
    {{- end }}
    {{- partial "comments.html" . }}
  {{- end }}

Reference

[1] How to Add Related Posts Section in Hugo