hugo

Is it possible to iterate over a pages within a section in hugo?


Im working with hugo v0.132.1 and I try to iterate through pages within a section in a partial in hugo.

I have the following structure:

content/
|-- references/
|   |-- ref1.md
|   |-- ref2.md
|   |-- ref3.md
layouts/
|-- partials/
|   |-- elements/
|       |-- slider-element.html/

The code inside slider-element.html looks like this:

{{ $references := where .Site.RegularPages "Section" "references" }}

{{ if gt (len $references) 0 }}
  <div class="slider">
    <div class="glide">
      <!-- Slider Struktur -->
      <div class="glide__track">
        <div class="glide__slides">
          {{ range $references }}
            <div class="glide__slide">
              <div class="reference-quote">
                <blockquote class="quote">{{ .Params.quote }}</blockquote>
                <div class="action-block cc-reference">
                  <a href="{{ .Permalink }}" class="button w-button">Zum Interview</a>
                  <div class="quote-block-source cc-reference">
                    <strong>{{ .Params.author }}</strong><br>{{ .Params.position }}
                  </div>
                </div>
              </div>
            </div>
          {{ end }}
        </div>
      </div>
    </div>
  </div>
{{ else }}
  <p>No references.</p>
{{ end }}

I have tried everything, but it always throws me an error execute of template failed at <where .Site.RegularPages "Section" "references">: error calling where: can’t iterate over <nil>

I have also created a layout for sections (layouts/_default/section.html) as well as a layout for the section references (layouts/section/references.html). But I still get this error.


Solution

  • Try:

    {{ $references := where site.RegularPages "Section" "references" }}
    

    In partials, it is sometimes easier to use the site global function rather than the .Site method, especially if you are accessing it inside loops.

    If you still have issues, I recommend:

    1. testing your code first outside a partial, directly in a layout, to make sure it works.
    2. testing access to site inside your partial, using a simple function such as site.Title
    3. inserting your code inside the partial once you confirmed access to site.