Conditional logic to display partial in nested sections

Hi!

I need help :slight_smile:. I am trying to find the way to insert conditional logic to a baseof.html for the “docs” section of my website to display sidebar menu only at some of the nested sections of the website.

My folder structure looks like this:

content
└── some-content-folder-1
    ├── page1.md
    ├── page2.md
    └── _index.md
└── some-content-folder-2 
    ├── page1.md
    ├── page2.md
    └── _index.md
└── docs
    ├── docs-folder-section-1 
        ├── page1.md
        └── _index.md
    ├── docs-folder-section-2
        ├── page1.md
        └── _index.md
...

After reading Sections | Hugo, I tried to use this one first:

{{ if and (eq .Parent.Section "docs-folder-section-1") (eq .Parent.Parent.Section "docs") }}
  <div class=" min-w-[216px] ">
    {{- partial "sidebar-docs.html" . -}}
  </div>
{{ end }}

However, the partial didn’t render at content/docs/docs-folder-section-1. Then I checked if Hugo treats it as a separate section by inserting this code in /docs/baseof.html:

Current Page Section: {{ .Section }}
<br>
Parent Page Section: {{ .Parent.Section }}
<br>

And got this:

Current Page Section: docs
Parent Page Section: docs

Then I could only achieve desired condition with the workaround like this:

      {{ if or (eq .FirstSection "docs") (in .File.Dir "docs-folder-section") }}
      <div class=" min-w-[216px] ">
        {{- partial "sidebar-docs.html" . -}}
      </div>
      {{ end }}

However, the latter seems like a hack, not the clean solution for a problem.
I would like to build the sidebar around that conditional logic for sections, so that it would render menu items of specific section where user is currently at.

Any kind of guidance is appreciated. Thanks!

What I would probably do in your situation would be to apply some metadata via

A tip is that you can also have a top level cascade section in your config file.

With glob matching you can match pages below a certain level etc. E.g. if you put this in content/_index.md and create a layouts/_default/sidebar-layout.html.

+++
[[cascade]]
layout = "sidebar-layout"
[cascade._target]
path = "/docs/docs-folder-section-1/**"
+++

Theres several ways to go about the above (a common way is to set the content type), but it at least shows the general principle

Thank you so much. That worked like a charm!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.