Matt McManis
Matt McManis

Reputation: 4675

How to List Pages in Current Section

I'm trying to list the pages in the current url section.


{{ range $value := .Site.Sections }}

    {{ range .Section }}

        {{ range $value.Pages }}
            <ul>
                <li>{{ .Title }}</li>
            </ul>
        {{ end }}

    {{ end }}

{{ end }}

Though it returns null because {{ range .Section }} is not valid code.

What is the correct way to do this?

https://gohugo.io/templates/variables/

Upvotes: 5

Views: 6930

Answers (1)

Jack Taylor
Jack Taylor

Reputation: 6217

You need to filter .Site.Pages by section using the where function. Try this:

<ul>
{{ range where .Site.Pages "Section" .Section }}
  <li>{{ .Title }}</li>
{{ end }}
</ul>

If you want to avoid empty lists, you can store the slice of section pages in a variable and check its length before you output the ul tags.

{{ $sectionPages := where .Site.Pages "Section" .Section }}
{{ if ge (len $sectionPages) 1 }}
  <ul>
    {{ range $sectionPages }}
      <li>{{ .Title }}</li>
    {{ end }}
  </ul>
{{ end }}

Upvotes: 12

Related Questions