Hi. I am creating a blog on HUGO and I need your help to implement a feature. For each post I will have a list of post titles
related: ["Title One", "Title Two", "Title Three"]
How to get records in a loop whose titles are specified in parameter related
? Thanks.
To implement the feature where you can display related posts based on their titles, you can use Hugo’s template and shortcode capabilities. Here’s a basic example of how you might do it:
Define your related titles in your front matter:
related:
- "Title One"
- "Title Two"
- "Title Three"
Create a shortcode to handle the related posts:
Create a file named related.html in your layouts/shortcodes directory:
{{ $related := .Page.Params.related }}
{{ range .Site.RegularPages }}
{{ if in $related .Title }}
<div>
<a href="{{ .Permalink }}">{{ .Title }}</a>
</div>
{{ end }}
{{ end }}
Now In your post template (e.g., single.html), call the shortcode where you want to display the related posts:
{{< related >}}
Let me know if you need any further assistance!
irkode
July 26, 2024, 3:54pm
3
to clarify: You may not call a short code from a template. You need a partial:
so it would be
layouts/partials/related.html
call it within your template as {{ partial "related.html" . }}
If you tend need to use it in your content file just wrap the partial call to a shortcode:
layouts/shortcodes/related.html
{{ partial "related.html" . }}
call it in your content file as {{< related >}}
1 Like
Arif
July 26, 2024, 6:28pm
4
This method is based on file path and might be more reliable since in case you change the titles in future
This is fundamentally the wrong way to do it, for a number or reasons:
The URL can can be affected by configuration (permalinks) and front matter (slug, url), but you’ve hardcoded the result.
By the same token, there is not an efficient way to perform a reverse lookup from URL to .File.Path, which is what you need in order to .GetPage
Instead…
---
title: Post 1
date: 2022-02-04T18:58:11.000Z
draft: false
related:
- /post/post-2
- /post/post-3
---
Then:
{{ with .Params.related }}
{{ …