My blog’s content structure looks like this:
- content
- posts
- hello_world
- index.md
- foo.jpg
Now I can easily reference images in index.md
like this:
![foo](foo.jpg)
But the problem is that when I tried to have preview of this post in home page, browser won’t be able to found the image because <img>
in html generated by Hugo used a relative src
by default, which is <img src="foo.jpg">
in this case. There’s nothing at <website>/foo.jpg
!
To address this problem, I write a Image render hooks in my theme in layouts/_default/_markup/render-image.html
:
{{- $img := .Page.Resources.GetMatch (.Destination | safeURL) -}}
{{- if $img -}}
{{- $resized := $img.Process "webp q75" -}}
<img src="{{ $resized.RelPermalink }}" alt="{{ .Text }}" {{ with .Title }} title="{{ . }}"{{ end }}>
{{- else -}}
<img src="{{ .Destination | safeURL }}" alt="{{ .Text }}" {{ with .Title }} title="{{ . }}"{{ end }}>
{{- end -}}
To prevent original jpg images being published, I added:
build:
publishResources: false
in the front matter of the post.
Everything looks good to me at first. In post page, it generated <img src="/blog/posts/hello_world/foo_hu17796280442050758554.webp">
, same as in index.html.
But the problem is that it creates duplicated image link in index.xml
, something looks like this:
<description><p>hello_world</p>
<p><img src="https://xxx.github.io/blog/blog/posts/hello_world/foo_hu17796280442050758554.webp" alt="hello" ></p></description>
Here’s my hugo.toml
:
baseURL = 'https://xxx.github.io/blog'
Did I missed something?