步骤 1 related.html
添加相关文章页面,在 layouts/partials
文件夹下新建 related.html
,代码如下。
layouts/partials/related.html
<!-- 找到当前文章所有标签相同的其他文章,但不包括当前文章自身,然后取前 5 篇这样的相关文章,赋值给变量 $related -->
{{ $related := first 5 (where (where .Site.Pages ".Params.tags" "intersect" .Params.tags) "Permalink" "!=" .Permalink) }}
<!-- 检查是否有相关文章存在。如果有,再执行下面的代码 -->
{{ with $related }}
<h3 class="see-also">{{- i18n "related" -}}</h3>
<div class="related">
<ul>
{{ range . }}
<li>
<a href="{{ .RelPermalink }}" target="_blank">{{ .Title }}</a> <span class="related-date">({{ .Date | time.Format "2006-01-02" }})</span>
</li>
{{ end }}
</ul>
</div>
{{ end }}
<style>
.post-footer h3 {
margin: 1.2em 0 1.2em;
}
.post-footer .related {
padding-bottom: 1.5rem;
}
.post-footer .related ul {
padding-inline-start: 20px;
}
.post-footer .related ul li{
list-style-type: square;
margin-bottom: 0.5rem;
}
.post-footer .related ul li a{
text-decoration: underline;
transition: color 0.3s ease-in-out, text-decoration-color 0.3s ease-in-out;
text-decoration-thickness: 1px;
}
.post-footer .related-date{
font-size: 0.8em;
font-style: italic;
}
.post-footer .related a:hover {
box-shadow: 0 1px;
text-decoration: none;
color: #ff5722;
text-decoration-color: #ff5722;
text-decoration-thickness: 2px;
}
</style>
步骤 2 single.html
调整 layouts/_default
文件夹下的 single.html
文件,在 <footer class="post-footer">
标签下添加代码。
<footer class="post-footer">
{{- if (.Param "ShowRelatedContent") }}
{{- partial "related.html" . }}
{{- end }}
{{- $tags := .Language.Params.Taxonomies.tag | default "tags" }}
<ul class="post-tags">
{{- range ($.GetTerms $tags) }}
<li><a href="{{ .Permalink }}">{{ .LinkTitle }}</a></li>
{{- end }}
</ul>
{{- if (.Param "ShowPostNavLinks") }}
{{- partial "post_nav_links.html" . }}
{{- end }}
{{- if (and site.Params.ShowShareButtons (ne .Params.disableShare true)) }}
{{- partial "share_icons.html" . -}}
{{- end }}
</footer>
步骤 3 语言翻译
i18n/en.yaml
- id: related
translation: "Related posts"
i18n/en.yaml
- id: related
translation: "相关文章"
步骤 4 调整配置文件
调整站点配置文件(hugo.yaml
),在 params
参数下新添 showRelatedContent: true
。
languages:
en:
languageCode: en-us
languageName: "English"
params:
author: Rickey
showRelatedContent: true
social: true
zh:
languageCode: zh-cn
languageName: "简体中文"
params:
author: 龚东海
showRelatedContent: true
social: true
感谢您的耐心阅读!来选个表情,或者留个评论吧!