Hugo基于标签展示相关文章

麦田4年前 (2019-09-03)工作笔记983

本文以主题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/

相关文章

国产静态博客生成器InkPaper纸小墨

在静态博客生成器/静态网站生成器领域,几乎都是国外的作品,InkPaper纸小墨则是国产的静态博客生成器,基于Go语言,生成速度很快!纸小墨自我介绍:InkPaper纸小墨是一个静态博客构建工具,可以...

Hugo主题nuo的配置

Hugo主题nuo简洁大方,电脑端界面分左右两栏,手机端界面和其他所有主题类似,我很喜欢!因为麦田喜欢生成.html文件,并直接放在网站根目录下,所以这个主题修改和配置的地方比较多:1、先设置网站根目...

Hugo主题maupassant的配置

编辑优化Hugo主题maupassant的经验因为在config.toml文件中添加了uglyurls = “true” ,生成的文件都是html格式,而不是默认的目录,所以就需要修改其他参数,比如标...

Hugo主题mainroad的配置

hugo主题模板mainroad源自WordPress主题 Mainroad,原作者是MH Themes,不得不说WordPress的主题最丰富,优秀作品也多。2020年2月20日优化:1、优化全部标...

Hugo主题jane的配置

麦田的博客是用Hugo搭建,主题是jane。jane主题添加关于我们和友情链接页面,并添加到页面菜单:新建md文件到文件夹content,重命名为about,页面头部加入:---title: &quo...

Hugo主题beautiful的优化

Hugo主题beautiful是个白灰色的主题,风格简洁,适合所有网站!这个主题的文件和内容比较混乱,尤其是CSS,编辑优化用了很多时间。遇到的第一个问题:语言解决方法是在配置文件里加入:defaul...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。