Deprecated .Page.Dir when in shortcode definition


I’m wondering about a warning message I have when building my site.

This is the message:

Building sites … WARN 2020/04/17 01:25:35 Page's .Dir is deprecated and will be removed in a future release. Use .File.Dir.

Here is the context:

I wish to highlight source code on a post page. So I use the highlight shortcode. The drawback of this shortcode is that I can’t directly read a plain source code file, I have to copy paste the content of the source file into the content/post page.
So I did a workaround by writing my own shortcode, that is:
{{- highlight ((path.Join .Page.Dir (.Get 0)) | readFile) (.Get 1) (print "linenos=table, style=" $.Site.Params.highlightTheme) -}}

And I use it like that:
{{< sourcecode "sourcecode/demo.c" "c" >}}

The goal is to mimic the behavior sphinx/reStructuredText’s literalinclude.

As you can see, I get that wrning because my shortcode definition is using Page.Dir to find the file path relative to the calling page.

However, if I use .File.Dir as adviced by the warning message, I get the following error:
executing "shortcodes/sourcecode.html" at <.File.Dir>: can't evaluate field File in type *hugolib.ShortcodeWithPage

It looks like the path is now relative to the shortcode definition file itself, which of course is pointless in this case.

And this is my question:

What is the recommended way to get the directory of the calling page in a shortcode definition ?

Else, is there an elegant workaround to solve this issue ?

Thank you very much,

You are inside a shortcode context, which does not have a .File variable, because .File is in the .Page context. So, try:


Yes, this solved my problem!

Thank you very much.

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