Hi All,
I have a small doubt on Hugo Related Pages. I have the code below which works great. It pulls all the related pages with the same tags and of type post.
{{ range first 3 (where (.Site.Pages.RelatedIndices . "tags") "Type" "post" ) }}
However, when I try to add Section
to the mix I am not able to get any posts. Itβs just that I am not sure how to code section into the range.
I want the related articles to be displayed based on similar tags based on the .Section
it resides in.
I know this is simple and I am breaking my head to figure this out. Sorry for the noob question.
Thanks
Iβm not sure that I understand your question.
content
content/
βββ book
β βββ book-1.md
β βββ book-2.md
β βββ _index.md
βββ post
β βββ section-1
β β βββ _index.md
β β βββ post-1.md
β β βββ post-2.md
β βββ section-2
β βββ _index.md
β βββ post-3.md
β βββ post-4.md
βββ _index.md
layouts/post/list.html
{{ range .Pages }}
<h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
{{ end }}
When I visit http://localhost:1313/post/section-1/
I will see:
Post 2
Post 1
When I visit http://localhost:1313/post/section-2/
I will see:
Post 4
Post 3
When I visit http://localhost:1313/post/
I will see:
Section 2
Section 1
Apologies if I was not able to make myself clear. My Sections and tags all work fine.
What I am looking for is Related Pages.
What I am trying to achieve is that when I open ../post-1.html
, for its related pages it should only show post-2
and or maybe other pages in section-1
with similar tags.
Hope this clarifies.
In my example I ranged through .Pages
instead of .Site.Pages
.
I apologize. I think I completely misunderstood your question. Both of these methods work. I broke these into several lines for clarity.
Method 1
{{ $related := .Site.Pages.RelatedIndices . "tags" }}
{{ $related = where $related "Type" "post" }}
{{ $related = $related | intersect .CurrentSection.Pages }}
{{ $related = $related | first 3 }}
{{ range $related }}
<a href="{{ .Permalink }}">{{ .LinkTitle }}</a>
{{ end }}
Method 2
{{ $related := .Site.Pages.RelatedIndices . "tags" }}
{{ $related = where $related "Type" "post" }}
{{ $related = where $related "CurrentSection.Path" .CurrentSection.Path }}
{{ $related = $related | first 3 }}
{{ range $related }}
<a href="{{ .Permalink }}">{{ .LinkTitle }}</a>
{{ end }}
Give it a try:
git clone --single-branch -b hugo-forum-topic-32420 https://github.com/jmooring/hugo-testing hugo-forum-topic-32420
cd hugo-forum-topic-32420
hugo server
Then visit http://localhost:1313/post/section-1/section-1-post-1/.
Files of interest:
- layouts/_default/single.html (this is where the βrelatedβ code resides)
- config.toml (includeNewer = true)
1 Like