How to get the URL of the current page with the rel or relref function?

I want to obtain the URL of the current page using {{< ref >}} or relref in the Markdown content of a post. Since ./ means the current path, I tried it but the returned value is not what I expected. I’ve created a minimal reproducible example with the latest version of Hugo at: https://jolly-mcnulty-eca481.netlify.app/source.zip I put the following code in the Markdown content of some .md files:

{{< ref "./" >}}
{{< relref "./" >}}

In the post https://jolly-mcnulty-eca481.netlify.app/post/2015/07/23/lorem-ipsum/, I was expecting relref "./" to return /post/2015/07/23/lorem-ipsum/ but it returned /post/ instead. Running ref on other files such as about.md or post/2015-07-23-lorem-ipsum/index.md returned the expected results.

For now, I could do ref "post/2015-07-23-lorem-ipsum/index.md", but if ref "./" works, that will be much better, since I wouldn’t need to worry about moving or renaming post files (no matter what the file path is, I could always pass "./" to ref, instead of having the path the actual full path).

Thanks!

Is the variable you’re looking for .RelPermalink?

Thank you! I almost typed "I was aware of .RelPermalink" in my original post because I was afraid that people would miss the specific scenario here. That is, I’m talking about the Markdown content of a post, instead of a template or a custom shortcode. .RelPermalink is only meaningful in templates or shortcodes. ref and relref are Hugo’s built-in shortcodes. Basically I was asking if they could recognize "./" as the input.

No, it doesn’t.

In the context of the ref or relref functions, it means the directory containing the current file. So the results you are seeing are correct.

As @funkydan2 suggests, use .Permalink or .RelPermalink within a shortcode.

layouts/shortcodes/permalink.html

{{ .Page.Permalink }}

layouts/shortcodes/relpermalink.html

{{ .Page.RelPermalink }}
1 Like

Okay, the context is the thing that I didn’t understand. Thanks for the explanation! So it seems there is no way to make ref return the URL of the current page, and the only way to go is to define a custom shortcode.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.