How to get the latest path element in the directory?

For nested sections, this is the latest path element in the directory, for example, /blog/funny/mypost/ => mypost.

You can use the .CurrentSection page variable for that. For your example .CurrentSection.Title will suffice, if I understand correctly?

It’s invalid when the page title and path are inconsistent.

I figured that might happen, but you didn’t tell in your post how (and if) you named your sections. So we’ll have to guess what works for your website.

You can also fetch the permalink of the parent section, and then strip that permalink from the nested section permalink.

So if the parent URL is /blog/funny/ and the nested section has a relative permalink of /blog/funny/mypost/, the result of stripping the latter with the first will be mypost/.

Code example:

{{ print "/" (strings.TrimPrefix .CurrentSection.Parent.RelPermalink .CurrentSection.RelPermalink) }}

Works for me. :slight_smile:

4 Likes

Thank you very much for your reply. It works for me too.

I suspect there is a simpler way… This is not tested:

{{ path.Base (path.Split .Path).Dir }}

The above is a mouthful, too, I guess, but slighly better.

2 Likes

Yes, It works. But I don’t find any explanation in the documentation about path.Base and path.Split

https://godoc.org/github.com/gohugoio/hugo/tpl/path

1 Like

Thank you very much for your patient answer. It’s a big help to me.