How to Create Custom Blocks in Hugo

Hongtao Hao / 2020-11-03


I thought creating custom blocks in Hugo would be difficult. But with Hugo’s shortcodes, and the CSS from Yihui Xie’s Bookdown project, it can be super easy.

Download images and edit stylesheet #

First of all, you’ll need to download five images from here : caution, important, note, tip, and warning.png. Add these images to the static folder of your Hugo project. I suppose you are adding them to the root directory of static.

Then, in your CSS stylesheet, add the following:

.note,
.important,
.tip,
.caution,
.warning {
  min-height: 2.2em;
  padding: 1em 1em 0.1em 4em;
  background: #f5f5f5 2px top/3em no-repeat;
} 
.note {
  background-image: url("../note.png");
}
.important {
  background-image: url("../important.png");
}
.tip {
  background-image: url("../tip.png");
}
.caution {
  background-image: url("../caution.png");
}
.warning {
  background-image: url("../warning.png");
}

Edit the styles as you need. For example, you can use a different font or font-size for texts in your custom blocks. If you don’t know how to do so, you probably need to learn more about CSS .

Also, background: #f5f5f5 2px top/3em no-repeat; means that the image will appear on the top-left corner. If you want it to be at the left-center, change that line of code to background: #f5f5f5 2px center/3em no-repeat;

Create shortcode #

Then, we are going to create shortcodes for custome blocks.

Create a shortcode named “block” (or any name you want) with the following code:

<div {{ with .Get "class" }}class="{{.}}"{{ end }}>

And another shortcode named “end” (or any other name you want) with the following code:

</div>

Super easy, right?

Write in between shortcodes #

This is a note.

is generated by:

{{< block class="note" >}}
This is a note.
{{< end >}}

The same is for important, tip, caution and warning.

This is important!

This is a tip. How much are you going to tip me?

Caution: Great food ahead! Stop if you are on a diet.

Warning: Road blocked ahead!

I personally use this quite often:

You can use this whatever way you like. I usually use it to remind myself something in a post.

If you like it too, you can download the image here , and then add the following codes to your stylesheet (edit as you need):

.reminder {
  min-height: 3.2em;
  padding: 1em 1em 1em 4em;
  background: #f5f5f5 2px center/3em no-repeat;
  background-image: url("../reminder.png");
}

You don’t have to use the name of reminder. Use any name you want.

Last modified on 2020-11-29