Get a Page's Folder Name in Hugo
Published: 2024-05-12 | Updated: 2024-05-16I needed the name of the folder in which a page was stored in order to make shortcode processing a little bit easier. Here’s how I managed to do it.
The key was being mindful of the type returned by the expression. I was using the path segment to filter on data living in .Site.Data
. The property I wanted to filter on was an integer - the year the data item was produced and recorded. So in order to get my shortcode to work I needed to convert the type of the value returned for the folder name from string
to int
{{ $y := int (index (last 1 (split page.Path "/")) 0)}}
Let’s break this down.
- The innermost parens split the page path into its path segments
- The
last 1
expression removes all but the last segment from the slice. The last segment is of course the folder name in which the page resides. - The index expression returns the value of the slice at the zero’th position.
- And finally the int expression returns the path segment as an integer value