Hugo基于标签展示相关文章
本文以主题rockrock为例讲解:使用dw打开模板文件:themes/主题rockrock/layouts/_default/single.html
找到以下内容:
</div>
{{ .Content }}
</div>
将展示相关文章代码放在上面这段话的下面。
相关文章代码有几种:
1、以下代码将匹配至少包含1个类似标签的文章/帖子/网页
<p>相关文章: </p>
{{ $currentPagePermalink := .Permalink }}
{{ $tags := .Params.tags }}
{{ range .Site.Pages }}
{{ $isMatchTags := intersect $tags .Params.tags | len | lt 0 }}
{{ if and $isMatchTags (ne .Permalink $currentPagePermalink) }}
<li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
{{ end }}
{{ end }}
2、推荐:限制相关文章的展示数量,一般建议数字10比较合理
<p>相关文章: </p>
{{ $.Scratch.Set "limit" 0 }}
{{ $currentPagePermalink := .Permalink }}
{{ $tags := .Params.tags }}
{{ range .Site.Pages }}
{{ $isMatchTags := intersect $tags .Params.tags | len | lt 0 }}
{{ if and $isMatchTags (ne .Permalink $currentPagePermalink) (lt ($.Scratch.Get "limit") 10) }}
<li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
{{ $.Scratch.Add "limit" 1 }}
{{ end }}
{{ end }}
3、以下代码实现两个功能:
查找并展示匹配至少2个标签的文章;如果找不到,查找包含1个标签匹配的文章,并限制为10个以内的文章。
{{ $.Scratch.Set "count" 0 }}
{{ $currentPagePermalink := .Permalink }}
{{ $tags := .Params.tags }}
{{/* range (where .Site.Pages "Section" "tutorials") */}}
{{ range .Site.Pages }}
{{ $isMatchTags := intersect $tags .Params.tags | len | lt 1 }}
{{ if and $isMatchTags (ne .Permalink $currentPagePermalink) }}
<a href="{{ .Permalink }}">{{ .Title }}</a>
{{ $.Scratch.Add "count" 1 }}
{{ end }}
{{ end }}
{{ if eq ($.Scratch.Get "count") 0 }}
{{ $.Scratch.Set "limit" 0 }}
{{/* range (where .Site.Pages "Section" "tutorials") */}}
{{ range .Site.Pages }}
{{ $isMatchTags := intersect $tags .Params.tags | len | lt 0 }}
{{ if and $isMatchTags (ne .Permalink $currentPagePermalink) (lt ($.Scratch.Get "limit") 10) }}
<li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
{{ $.Scratch.Add "limit" 1 }}
{{ end }}
{{ end }}
{{ end }}
感谢原作者,本文来自:https://code.luasoftware.com/tutorials/hugo/hugo-show-related-posts-by-tags/
相关:https://www.qd1024.com/post/hugo/