Method for calling a nested section's title

Given the following content structure with a nested section, like this:

content/
	section/
	  _index.md
	  entry-one.md
	  nested-section/
	    _index.md
	    entry-one.md

And assuming my nested section’s _index.md file has a title key.

I can get my nested section’s title with this

{{ $sections := (.Site.GetPage "section" .Section).Sections }}

{{ $this_section := index (where ($sections) "Dir" .Dir) 0  }}

then call the section title with something like this (my actual code is a little more complete, but this is the idea):

{{ if $this_section }}
	{{ $this_section.Title }}
{{ end }}

I don’t know if this is a tip or an ask for help :slight_smile: but this is the best way I’ve found yet to do accomplish getting at that data, having looked around here, the code/docs and the nested section’s sample. And nested sections are new, so perhaps I’ve missed the actual direct method or there will be one in the future.

1 Like

Not sure why you don’t go directly at the nested-section:

(.Site.GetPage "section" "section" "nested-section").Title
```

Or:


(.Site.GetPage “section” “section/nested-section”).Title

Can I do that if I don’t know the name/directory of the section in advance?

In your simple case, yes,

(.Site.GetPage "section" "section" .Dir).Title

There is an issue about adding more section related accessors to simplify stuff. We should get that done for the next Hugo, we have an unexported method that returns the “current section”, which I guess would be useful in this case.

That doesn’t work for my actual use case (maybe because I’m allowing for multiple nested sections?), but that’s helpful in thinking through it. So I have something until there’s a more efficient method.

And, for what it’s worth, what I have also lets me pull in additional parameters from the nested section. I use Title and Name so I can have different values for list and singular views.

By the way. I only threw that last bit in there in case it’s any sort of consideration as you flesh out the current section method further.

I tried this, but it didn’t work because .Dir outputs the directory with a trailing /
.Dir outputs section/nested-section/

From what I saw, .Site.GetPage expects the last parameter to be like section/nested-section. No / at the end.

I solved it like this:

{{ $x := sub (countrunes .Dir) 1 }}<br/>
{{ $trimmed_dir := slicestr .Dir 0 $x }}
{{ (.Site.GetPage "section" $trimmed_dir).Title }}

It works, but it doesn’t seem like an elegant solution.

I’m also using that to create a default section template that works for all nested sections:

{{ $this_section := ($.Site.GetPage "section" $trimmed_dir).Sections }}
{{ range $this_section }}
   ...
{{ end }}

Is there a nicer way to achieve this?

1 Like

@guayom For my use-case, I’m using this:

{{ $section := index (where ((.Site.GetPage "section" .Section).Sections) "Dir" .Dir) 0  }}