From 9f5b8e8059e61edbf4faa8df999173096afefa98 Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Wed, 30 Oct 2024 23:43:32 +0530 Subject: [PATCH] Support relative paths in markdown images MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds code from Hugo's built-in render-image hook and modifies it slightly to support relative image paths in markdown files. Previously, we'd have to spell the absolute path from root of the hugo site or make directories for each individual post which is what Hugo recommend. But this was very inefficient. This change allows us to use editors like Obsidian, VSCode and have them render the images correctly. It also supports Hugo's page bundles for rendering images as a result. Based on the order, I believe page bundles are given priority so that works out. i.e, if you have the following tree: ``` content └── posts ├── _index.md ├── hello.md ├── images │ └── test.png └── test.png ``` You can now include images in `hello.md` in the following ways: ``` ![](test.png) ![](images/test.png) ![](./test.png) ![](./images/test.png) ``` --- layouts/_default/_markup/render-image.html | 32 ++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/layouts/_default/_markup/render-image.html b/layouts/_default/_markup/render-image.html index 25d893e..0930316 100644 --- a/layouts/_default/_markup/render-image.html +++ b/layouts/_default/_markup/render-image.html @@ -1,5 +1,33 @@ +{{/* +To get page resources and relative paths to work. Copied as is from default +hook: +https://github.com/gohugoio/hugo/blob/89bd02/tpl/tplimpl/embedded/templates/_default/_markup/render-image.html +*/}} +{{- $u := urls.Parse .Destination -}} +{{- $url := $u.String -}} +{{- if not $u.IsAbs -}} + {{- $path := strings.TrimPrefix "./" $u.Path -}} + {{- $imgResource := .Page.Scratch.Get "typoNilVariable" -}} + {{/* Check if this is a page bundle or standalone page */}} + {{- if .PageInner.Resources -}} + {{- $imgResource = .PageInner.Resources.Get $path -}} + {{- else if (or .PageInner.Parent .PageInner.Parent.Resources) -}} + {{- $imgResource = .PageInner.Parent.Resources.Get $path -}} + {{- end -}} + {{- $imgResource := or $imgResource (resources.Get $path) -}} + {{- with $imgResource -}} + {{- $url = .RelPermalink -}} + {{- with $u.RawQuery -}} + {{- $url = printf "%s?%s" $url . -}} + {{- end -}} + {{- with $u.Fragment -}} + {{- $url = printf "%s#%s" $url . -}} + {{- end -}} + {{- end -}} +{{- end -}} + {{/* Split URL at # */}} -{{ $url := .Destination | safeURL }} +{{ $url = $url | safeURL }} {{ $file_name_array := split $url "#" }} {{/* @@ -18,7 +46,7 @@
- {{ .Text }} + {{ .Text }}
{{ with .Title }}