Nested list of sections and content - Hugo

Viewed 765

I have a series of nested sections that contain recipes, grouped by type of dish, e.g.:

content
└─ recipes
   ├─ _index.md
   ├─ bread
   │  ├─ _index.md
   │  ├─ beer_rolls.md
   │  ├─ ciabatta.md
   │  └─ potato_bread.md
   ├─ dessert
   │  ├─ _index.md
   │  ├─ chocolate_brownies.md
   │  ├─ elderberry_pie.md
   │  └─ victoria_sponge_cake.md
   └─ mains
      ├─ _index.md
      ├─ bean_chilli.md
      ├─ braised_leeks.md
      └─ yorkshire_pudding.md

I want to write a list.html for content/recipes/_index.md, to produce a nested list that reflects the directory structure in recipes/, such that the first level of the list links to the subsection e.g. bread or dessert, and the second level of the list links to the individual recipes, e.g. bread/beer_rolls.md or mains_bean_chilli.md.

What does the list.html contain? Do I need to have multiple list.html files, one for each nested subsection?

1 Answers

With help from this example, I constructed the following system, which works well for me:

in layouts/recipes/list.html I included this:

{{ if (eq .Title "Recipes") }}
  <ul class="postlist">
    {{ range .Sections.ByTitle }}
      <li>            
        <a href="{{ .RelPermalink }}">{{ .Title }}</a>
        {{ partial "recursive.html" . }}
      </li>
    {{ end }}
  </ul>
{{ else }}
  <ul class="postlist">
    {{ range .RegularPages }}
    <li>
      <a href="{{ .RelPermalink }}">{{ .Title | markdownify }}</a>
    </li>
    {{ end }}
  </ul>
{{ end }}

And in layouts/partials/recursive.html I included this:

{{ $child_pages := union .Sections .Pages }}
<ul>
  {{ range $child_pages.ByTitle }}
  <li>                                    
    <a href="{{ .RelPermalink }}"> {{ .Title }} </a>
    {{ if or (.Sections) (.Pages) }}
    {{ partial "recursive.html" . }}
    {{ end }}
  </li>
  {{ end }}
</ul>

content/recipes/_index.md looks like this:

---
title: "Recipes"
---

and for example content/recipes/drinks/_index.md looks like this:

---
title: "Drinks"
---

This produces a page at ./recipes which contains a grouped list, where the first level includes links to further list pages (e.g. ./recipes/bread), which themselves contain links to the recipes in that group. All recipes are also listed below their parent group on ./recipes.

Related