How to get posts by their titles in an array?

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!

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

This method is based on file path and might be more reliable since in case you change the titles in future