I am using HUGO with the ananke theme. In the main config.yaml
, I define the baseURL
as follows:
baseURL: "https://username.github.io/myblog"
I put some images in static/images
. Say, I want to include the image both, as featured_image of a post and in the post itself. By trial and error, I found that the URL in the frontmatter should be
---
featured_image: "/images/myimage.jpg"
---
However, to include the image in the post body, I need to use the URL
[my image](/myblog/images/myimage.jpg)
..otherwise the effective URL will be https://username.github.io/images/myimage.jpg
.
That does not make any sense to me. Why are the two different? Why does [my image](/images/myimage.jpg)
not work, when featured_image: "/images/myimage.jpg"
works? Can you explain?
First problem is that maybe one day I decide to move the site - and I don't want to have to check / replace each and every myblog/
path. The second problem is that I would like actually to have a slightly different hierarchy, where each posts lives in its own directory, along with its media files. However, I apparently don't understand how these URLs are created.
The post body uses Markdown rules, so by default, it just puts the URL that you indicate between the parenthesis, either absolute or relative. It does not consider .baseURL
.
See Markdown doc for more information
To avoid this issue, you can modify Hugo image render hook by creating a file layouts/_default/_markup/render-image.html
, to add .baseURL
to all your images.
Original version (this file does not exists by default, but this is the code use, according to the documentation):
<p class="md__image">
<img src="{{ .Destination | safeURL }}" alt="{{ .Text }}" {{ with .Title }} title="{{ . }}"{{ end }} />
</p>
Modified version (you create this file and it will be used, instead of the default version):
<p class="md__image">
<img src="{{ .Page.Site.BaseURL }}{{ .Destination | safeURL }}" alt="{{ .Text }}" {{ with .Title }} title="{{ . }}"{{ end }} />
</p>
Be careful:
.BaseURL
param from inside the render-image.html
, which is a specific context. You need to go through .Page.Site
.Destination
starts with //:
, https://
or https://
, not to add the /myblog before.