How to pass a list of pages to a shortcode?


#1

I feel like this should be really simple, but I’m stuck (spent several hours). What I’m trying to do is this:

   {{< related "post1" "post2" >}}

And then I want to render a list of links to these pages in the related.html shortcode template (using Hugo 0.48):

{{ $related := false }}
{{ if .Params }}
{{ $related = (apply .Params ".Site.GetPage" ".") }}
{{ else }}
{{ $related = .Site.RegularPages.Related .Page | first 5 }}
{{ end }}
{{ if $related }}
<section class="related">
    <h2>See also:</h2>
    <ul>
            {{ range $related }}
            <li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
            {{ end }}
    </ul>
</section>
{{ end }}

The error I’m getting is "error calling apply: can't find function .Site.GetPage".


#2

I haven’t reviewed all of your code. But specific to this error, use $.Site instead of .Site.


#3

The apply func only works with template functions. Not methods.


#4

Ok, solved this by duplicating the markup:

{{ if .Params }}
<section class="related">
    <h2>See also:</h2>
    <ul>
        {{ range .Params }}{{ with $.Site.GetPage . }}
        <li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
        {{ end }}{{ end }}
    </ul>
</section>
{{ else }}
{{ with .Site.RegularPages.Related .Page | first 5 }}
<section class="related">
    <h2>See also:</h2>
    <ul>
        {{ range . }}
        <li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
        {{ end }}
    </ul>
</section>
{{ end }}
{{ end }}

The shorcode could be used as follows:

  1. Automatic related posts
{{< related >}}
  1. Explicit related posts
{{< related "post1" "post2" />}}