HUGO

How to know if a page belongs to a sub-section?

In my template {{ .Section }} returns the parent section name, but my page belongs to a nested section

section/nested-section/test-page.html

In my template, how do I get the following:

  1. “nested-section” from test-page.html
  2. If a page belongs to section level 1 or 2. Basically if my page is two or one level deep

Thank you!

Without directly answering your quesition, every page has a .Parent, .CurrentSection, .IsAncestor and .IsParent and .Sections

1 Like

Without directly answering your quesition, every page has a .Parent, .CurrentSection, .IsAncestor and .IsParent and .Sections

None of these options carries the value I’m looking for.

I’ve got a catalog of products. The parent section is called “catalog” and the nested section is called “portal”. There I have one file for each product in that category, so: “/content/catalog/portal/product-1.html, /content/catalog/portal/product-2.html, etc.”

I have the same template for any sub-section in catalog, i.e. “/layout/catalog/single.html”. There I’d like have the name of the current section I’m in, i.e. “portal”.

I looked everywhere in the docs, tried debugging the object “.”, “.Page”, “.Section”, “.CurrentSection”, etc. I can’t find this information anywhere. The best I could find is, by printing the object “.” there’s a unexported key called “targetPathDescriptor”. There I have an exported key called “Sections” that is a slice of strings looking like this string[] {"catalog", "portal"}. But since it’s under an unexported key I can’t have it.

How do I do it?

3 Likes

Just because this shows up in Google Searches, thought it is old, and bep was correct in pointing that every page does have the necessary information. I had the same problem and wish to be helpful:

Let’s say we have:
Case 1:
/1st-dir/foo.md
Case 2:
/1st-dir/1st-nested-dir/moo.md

{{ if ne (path.Base .Dir) .Section }}

In case 1:
The above test will be false.

In case 2:
The above test will be true.

So in the question "How do I get the following:

  1. “nested-section” from…
  2. If a page belongs to section level 1 or 2…

Q1: (in this case “moo.md”) path.Base .Dir will give this.
Q2: This is unfortunately a badly worded question, I will answer Q2-2 (2 level) and Q2-1 (1 level)
{{ if ne (path.Base .Dir) .Section }} Will give a false for level 1 and true for level 2.

{{ if (path.Base .Dir) .Section }} Will give a true for level 1 and false for level 2.

Please, anyone sidecheck me but I searched some time for the answer and the above worked for me, I hope to be of help to others.