How to use render hooks in hugo
Today I learned how to overwrite default templates used by #hugo to change the image lookup and the link click targets.
Motivation
In my first post Hello Hugo I described the workflow on how I use obsidian as my content source when generating the static blog using hugo. During that process I encountered the problem of having a mismatch of the image path generated by hugo and the image path inside my markdown files. In order to make it work in hugo I had to do something like this in obsidian as a workaround:
With this syntax, the generated images were displayed correctly inside the generated html code, but inside obsidian the display was broken. During my research on how to change this I stumbled accross Hugo Markdown Render Hooks .
Render Hooks FTW
With hugos Markdown Render Hooks it is possible to change the behaviour of how markdown tags are rendered. Those hooks can be created inside the themes folder under themes/archie/layouts/_default/_markup/
.
Image Tag Layout
For my initial problem I simply added ../
to the <img src="
part of the img hook I created inside
../themes/archie/layouts/_default/_markup/render-image.html
.
<img src="../{{ .Destination | safeURL }}" alt="{{ .Text }}" {{ with .Title }} title="{{ . }}" {{ end }} />
This already fixed the image path mismatch between obsidian and hugo.
Link Tag Layout
The second adjustment I wanted to make is to open links in a new instead of the current browser tab. For that I created the following markdown render hook at ../themes/archie/layouts/_default/_markup/render-link.html
<a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }} {{ if strings.HasPrefix .Destination "http" }} target="_blank" {{ end }} >{{ .Text | safeHTML }}</a>
I only want this for external links, so I added an if statement which checks if the link starts with http
. If yes -> add target="_blank"
. For all internal links the current browser tab was used.