Can't access .Data.Pages (or .Site.Pages) inside another range

Hi All,
I’m new to Hugo but loving it so far! I’ve hit a problem that I can’t seem to get around though.

I’m trying to build a homepage that has various sections or blocks that are optionally displayed according to configuration in the page’s front matter (I’m setting this up using and using their front matter templates to make this configurable for an end user)

I’ve recreated the issue in a test site. The problem is illustrated by this template I’m using for the home page:

{{ partial "header.html" . }}
    <h1>{{ .Title }}</h1>
    {{ .Content }}
    {{ range .Params.blocks }}
        {{ if eq .template "home-page-riding-packages" }}
            <h2>This range gives an error... 'can't iterate over &lt;nil&gt;'</h2>
            {{ range where .Data.Pages "Section" "packages" }}
                {{ .Title }}
            {{ end }}
        {{ end }}
    {{ end}}

    <h2>This range works...</h2>
    {{ range where .Data.Pages "Section" "packages" }}
        <p>{{ .Title }} - {{ .Params.custom1 }}</p>
    {{ end }}

{{ partial "footer.html" . }}  

I’m using ‘range’ to iterate over the blocks and then checking the template value to know whether to display the block or not. If I try to range over .Sites.Pages or .Data.Pages. within this outer range I get an error saying that I can’t iterate over nil - the list of pages is empty. Further down in the example, outside of the outer range, I can list the pages and they are displayed correctly.

I’m guessing that the outer ‘range .Params.blocks’ call is rebinding the scope of . to the block in my data, which is why the .Data.Pages or .Sites.Pages doesn’t then work.

Anyone have any ideas how I can do this? I’ve been trying all sorts of things to try and fix this.

Any help would be greatly appreciated - I’ve been stuck on this since yesterday and I’m rapidly running out of hair to pull out :wink:



{{ range where $.Data.Pages "Section" "packages" }}

Also note that when you do “section filtering” in a where clause, I suspect that you will always want something ala:

{{ range where $.Site.RegularPages "Section" "packages" }}

I’m sure that was one of the things I tried… but adding the $ works. Thanks for that - you’re my hero!

This may clarify things:

Thanks so much that article is super helpful.

1 Like