Welcome back to the Hugo series. In our last post, we added an RSS feed to our site. In this post, we are going to look at how to extend the output of the HTML that is generated by Hugo for a post.
When creating a post, there are times where you really wish Hugo could render something fancier than the basic HTML that markdown to html provides. Maybe you want to add a caption to an image or embed a YouTube video or include a gist. You could embed the HTML within your markdown file, but that makes your markdown file messy, harder to read, and a bit of a pain if you need to update the HTML across all your posts.
This is where Hugo shortcodes come into play. Shortcodes are simply a way of inserting a snippet of HTML into a page from your markdown.
Let’s take a look at how to use the built-in shortcodes.
Note: shortcodes only work in markdown file, not template files. If you need the type of functionality that shortcodes provide but in a template, you want a partial template instead.
For our walk through, we are going to use the YouTube shortcode to embed a responsive video player for YouTube videos. I am going to use https://www.youtube.com/watch?v=wHtu5NQof_Y
for the video.
For the shortcode, we just need to pass the YouTube video ID that follows v= in the video’s URL to the youtube shortcode
{{< youtube wHtu5NQof_Y >}}
However, for accessibility, you should provide a title for your YouTube video else it will just say “YouTube Video” which is not helpful to let someone know what the video is about. You can include a title by providing a title parameter in the shortcode.
Note: You can’t mix named and unnamed parameters, so you’ll need to assign video id to the parameter id
{{< youtube
id="wHtu5NQof_Y"
title="Level up on Functional Programming by Rebuilding LINQ with Cameron Presley" >}}
The video will be rendered as:
Here is the HTML that was generated from the shortcode
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
<iframe src="https://www.youtube.com/embed/wHtu5NQof_Y" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;" allowfullscreen title="Level up on Functional Programming by Rebuilding LINQ with Cameron Presley"></iframe>
</div>
As you can see, shortcodes are a powerful and easy way to include additional html to enhance your pages while keeping your markdown clean.
There are several shortcodes that are included in Hugo.
- figure
- highlight
- YouTube
- gist
- tweet
- Vimeo
See how to use the built-in shortcodes in the Hugo Shortcodes Documentation
In our next post, we will take a look at how you can create your own shortcodes.