Attach specific posts to a post


#1

Is there a way to attach/embed specific posts in Hugo?

I have a reviews section and a products section. In my reviews I would like to attach/embed the products and display their content and metadata. I’ve solved this in Wordpress in Advanced Custom Fields, is there a way to do it with Hugo?

Could I write a shortcode and make use of the relref-funcionality?


#2

In the docs: https://gohugo.io/content-management/page-bundles/#readout

Is that what you mean?


#3

If your products are regular pages which have their own pages on the site, then you should look toward Related Content.

I wrote a piece about how this feature can help you achieve what you want:


#4

Also you can use .GetPage


#5

Yeah. This works. Any idea how I would implement with a shortcode?

I tried this but I couldn’t get it to work.

Shortcode:
{{< shortcode path-to-post >}}

Template (shortcode.html):

{{ with .Site.GetPage "page" "section" "{{ .Get 0}}.md" }}
{{ .Title }}
    {{.Summary}}
{{ end }}

#6

When something doesn’t work, it’s always nice to show precisely what kind of data you fed it, what what it output, or what error it produced. This makes it way easier to get some help :slight_smile:

I can already tell you that as far as I know nested brackets is not possible in go templates. The brackets delimit what’s compiled from what’s left intact in the output. So here you’re already in a go part of your template, you can’t introduce {{ .Get 0}} like this.

For this kind of purpose we usually use printf like so:

printf "%s.md" (.Get 0)

You may need to put additional parenthesis around the whole expression so that it’s considered as one argument by the GetPage function.


#7

I think we are on the right track here, but trying to implement it like this:

{{ with .Site.GetPage "page" "section" "(printf "%s.md" (.Get 0))" }}

I get:
unexpected "%" in operand


#8

printf returns a string, so you don’t double-quote that printf expression.

Also, as that code is within a shortcode, you would need to use the “root context” $… So $.Site. .. instead of just .Site. ...

… and specifying the .md extension in the .GetPage expression is optional.


#9

The double-quote was the issue.