Proper URL for images in page bundles

I’m writing a post in content/posts/mypost/index.md and have an image content/posts/mypost/image.png that I want to display in the post.

I want to use the figure shortcode. I have to specify src="/some/path". I thought if I just put src="image.png" than it would handle it as a relative URL and that would work, but it doesn’t.

What’s the proper way of specifying the URL?

Also, how does all this relate with things like .Resources.Match, why can’t I use this with shortcodes? Or can I? If so, how? What’s the correct way of embedding an image into a post?

Easiest is to use images is in page bundles, should have no problem with relative paths then.
Page Bundles | Hugo (gohugo.io)
Then
Option 1. use a render hook, add an image in the usual markdown way and make it a figure element in the render hook
Markdown Render Hooks | Hugo (gohugo.io)
Option 2. use a shortcode, not sure how the built in figure shortcode works but you can roll your own.

{{< fig src="myrelativeimageinsamefolderasindexmd.jpg" alt="alt text" caption="caption">}}

Then grab those in the shortcode and process however you like, to match the built in it will be something like:

{{- $src := $.Page.Resources.GetMatch (.Get "src") }}
{{- $alt := .Get "alt" -}}
{{- $caption := .Get "caption" -}}
<figure>
  <img src="{{$src.RelPermalink}}"  alt="{{ $alt }}"/>
  <figcaption>{{$caption}}</figcaption>
</figure>

But you can do better, e.g. add a webp version and some responsive sizes with a picture element instead of a simple img.

Thanks for the example code!

I’m still wondering how the built-in figure shortcode is implemented. If I can only pass global URLs, this would be a really bad shortcode. I thought built-in shortcodes are sort of ideal in what they do, because the Hugo developers themselves developed them?

(Perhaps you can comment @bep, but only if you have the time!)

I just found out that the <base> tag in the head was the issue that made all links absolute. I removed it and now I can also use local links.

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