How to get the current url in Hugo
By Flavio Copes
Learn how to get the current URL in Hugo using the .Page.RelPermalink value, trimming the slashes to get a clean relative path like ebooks or ebooks/php.
To get the current URL in a Hugo template, use .Page.RelPermalink. It returns the path of the page being rendered, relative to the site root:
{{ .Page.RelPermalink }}
For a page served at yoursite.com/ebooks/, this prints /ebooks/.
If you want the full URL including the domain, use .Page.Permalink instead. That one gives you https://yoursite.com/ebooks/, built from the baseURL set in your site config. It’s what you want for canonical links and og:url meta tags.
Getting a clean path
RelPermalink comes with a leading and a trailing slash. Sometimes you want just the path segment, without slashes. Wrap it in trim:
{{ trim .Page.RelPermalink "/" }}
This is the result:
yoursite.com/ebooks -> "ebooks"
yoursite.com/ebooks/php -> "ebooks/php"
trim removes the characters you pass (here, /) from both ends of the string, so the slash between ebooks and php survives.
When do you need this?
The classic use case is highlighting the active item in a navigation menu. You compare the current page’s URL with each link:
<a href="/blog/" class="{{ if eq .Page.RelPermalink "/blog/" }}active{{ end }}">
Blog
</a>
I’ve also used the trimmed version to build CSS class names or id attributes based on the page, so each section of the site can get its own styling hook.
Watch out inside range loops
Inside a range loop, the dot changes. It points to the current item of the loop, not to the page being rendered. So .Page.RelPermalink there gives you the URL of the item, which is often exactly what breaks an active-menu check.
The fix is $, which always refers to the context the template started with:
{{ range .Site.Menus.main }}
<a href="{{ .URL }}" class="{{ if eq $.Page.RelPermalink .URL }}active{{ end }}">
{{ .Name }}
</a>
{{ end }}
One more detail: with Hugo’s default pretty URLs, RelPermalink ends with a trailing slash. Compare against /blog/, not /blog, or the check never matches.