How to embed partials in Markdown Using Hugo

Last modified March 22, 2021
.* :☆゚

It is usually very finicky to embed and process markup in markdown files when dealing with static site generators.

Here is a neat trick you can use in Hugo to embed live HTML/CSS/JS in individual files, using Hugo’s shortcodes and filters.


Make the shortcode

In your shortcodes folder (should be under layouts, as per Hugo’s file structure), create a new file called embed.html.

Paste the following code into the file and save.

{{ $file := .Get "file" }}
{{- $file | readFile | safeHTML -}}

This essentially creates a global shortcode that can be referenced by the file’s title, in this case, embed.

Save the markup you want to embed in a separate file

To keep things clean, I recommend creating a new folder in the static folder of your project, and name it however you wish to reference it. Create a new html file inside this folder, and save it with whatever code you wish to embed.

Embed your code in a markdown file

You can now use your embed shortcode anywhere in a markdown file in Hugo using the following method:

{{< embed file="/static/__YOURFOLDERTITLE__/__YOURFILE__.html" >}}

In my case, I have a folder called modules in my static folder, and I save all embedded code snippets in there if I ever want to reference it in a blog post.

And that’s it! You should now be able to view your saved html partial right in your markdown generated post.

Jaclyn Tan

I'm Jaclyn and I make websites. I aim to make the web a more fun and accessible place, sharing what I learn along the way.

My blog has no ads or sponsors and I plan on keeping it that way. If you like what I do please consider supporting me.