在使用 Hugo + PaperMod 主题写博客时,文章之间往往是割裂的。如果能在文章底部给出一些相关文章的入口,不仅对读者友好,也能顺带提升站内浏览深度。
这篇文章记录一次在 PaperMod 主题中,通过标签匹配的方式,在文章底部添加相关文章列表的实践过程。
1.新建页面
首先在 layouts/partials 目录下新建一个 related.html,专门用于生成相关文章列表
该模板会:
- 找到与当前文章 标签相同 的其他文章
- 排除当前文章自身
- 最多取前 5 篇作为相关文章展示
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 }}
2.添加样式
接下来为相关文章区域补充样式
在 assets/css/extended/ 目录下新增 related.css
.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;
}
3.调整 single.html
最后在文章页模板中引入该 partial
修改文件: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>
通过 ShowRelatedContent 参数进行控制,可以按文章粒度决定是否展示相关文章
至此,文章底部的相关文章模块就完成了
如果本文对你有所帮助,可以请我喝杯咖啡
(完)