Converting related content code to a shortcode

Hello, I use:

{{ with site.RegularPages.Related . | first 5 }}

<p>Related content:</p>
  <ul>
	 {{ range . }}
	   <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
	 {{ end }}
  </ul>
{{ end }}

successfully without errors in my page.html template.

So that I could use the same code in only some pages, I created a shortcode and put the same code in it and get errors:

execute of template failed: template: _shortcodes/related-pages-shortcode.html:1:13: executing “_shortcodes/related-pages-shortcode.html” at <site.RegularPages.Related>: error calling Related: invalid argument type *hugolib.ShortcodeWithPage

I have spent hours and hours trying to debug this. I have asked AI for help, it can often be very helpful but in this case makes suggested changes, which still cause errors, and then makes more changes which still causes errors, over and over.

Any help on this would be much appreciated. Thanks ahead of time for any assistance.

Haven’t tested, but with Hugo shortcodes, use .Page or $.Page to pass context instead of site.

1 Like

the site call is not the problem. site is a global.

it’s the dot context that point to the shortcode use .Page instead.

1 Like

@kijana Thank you for your quick reply. I tried

{{ with .Page.RegularPages.Related . | first 5 }}

and it did not give an error but did not display any related content.

@irkode Thanks very much for your quick reply and providing the solution :slight_smile:

Using:

{{ with site.RegularPages.Related .Page | first 5 }}

works great. Much appreciated.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.