Get a Page's Folder Name in Hugo

Published: 2024-05-12 | Updated: 2024-05-16

I 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.