HUGO

Is there a way to control markdown images in Hugo?

I’m looking at Markdown WYSIWYG editors at the moment and naturally when an image is inserted it uses the default markdown syntax e.g. ![Photo of someone](/images/1.jpg) and then the output is simply an img element with an alt attribute.

But is there a way to manipulate this simple img element in Hugo without having to modify the .md file?

For example I would like the markdown image to be automatically wrapped inside a figure element or give it a class attribute etc.

Maybe Hugo should have an internal shortcode to handle images that are inserted with the markdown syntax, so that a user can override it and set it according to her/his needs…

It would be a very cool feature by the way.

For example one could just include Pen https://sofish.github.io/pen/ as a simple frontend for a Hugo site, create an .md, save it and then publish on the fly.

Or just use Dropbox Paper. There are a lot of options out there.

There is a figure shortcode: https://github.com/spf13/hugo/blob/master/tpl/tplimpl/template_embedded.go#L21
https://gohugo.io/content-management/shortcodes/#figure

But you could also do Replace: https://gohugo.io/functions/replacere/

As far as I have tested, Hugo’s internal figure shortcode doesn’t catch images with the markdown syntax.

I may be wrong though.

Edit

I have been playing with replace.

And the options that go with replace.

safeHTML ignores the markdown syntax.

Plainify doesn’t work. It breaks everything as does markdownify.

Doing a regex with replaceRE I’m not quite sure how to do that…

Essentially I am trying to wrap the img into the markup I want, but it doesn’t work and also there’s no way to output the alt attribute as a caption, using the replace route.

1 Like

This can’t be done in Hugo natively -at least not entirely-. I very much doubt that filling a Github issue would make much of a difference since there are other priorities.

BUT

I managed to wrap a markdown image with the markup I need, by modifying line 824 of pen.js https://sofish.github.io/pen/

from

img: [/<img\b[^>]*src=["']([^\"+|[^']+)[^>]*>/ig, '![]($1)']

to

img: [/<img\b[^>]*src=["']([^\"+|[^']+)[^>]*>/ig, '{{% wrap %}}![]($1){{% /wrap %}}']

It’s very simple really. I just wrapped the markdown image inside a Hugo shortcode that uses markdown {{% wrap %}} so that on markdown export I get what I need!

Profit! :sunglasses:

Who needs a CMS with PHP etc when one can do his job with a simple WYSIWYG frontend like Pen.

Now on to the next challenge! :beers:

1 Like

For posterity I want to point out that since Hugo v.0.62.0 users can have full control over the rendering of Markdown syntax images without shortcodes.

See: https://github.com/gohugoio/hugo/releases/tag/v0.62.0