Info card shortcode for Hugo

If you are using Hugo as your static site generator, you might want to create a card shortcode that can display different types of information on your blog posts. A card is a small rectangular element that can show an image, a title, a subtitle, and some text.

In this post, I will show you how to create a card shortcode that can accept both predefined data and custom data that you can pass from your Markdown file.

Please note that, this post is assuming that you know how to make a blog in Hugo and what is shortcodes in Hugo.

Custom Info card shortcode

The data depends on the header parameter that you specify in the Shortcode. For example, if you use the Shortcode below, it will check if the header value matches any of the cases in the if statement. If it does, it will display the corresponding data. If not, it will display the content value that you provide in the Markdown. You can also add a title to the card by using the title parameter

Card with predifned data

Below example showing how you can display a predifined content using this shortcode.

Shortcode

{{/* < info_cards header="lorem-ipsum" title="What is Lorem Ipsum?"  > */}}

Output

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Card with custom data

Below example showing how you can display a custom content using this shortcode.

Shortcode

{{/* < info_cards header="custom" title="What is a shortcode?" 
content="A shortcode is a simple snippet inside a content file that Hugo will render using a predefined template." > */}}

Output

What is a shortcode?

A shortcode is a simple snippet inside a content file that Hugo will render using a predefined template.

Below is the code for above custom shortcode.

info_cards.html

{{ $header := .Get "header" }}

<div class="card mb-3 bg-light">
    <div class="card-body">
        {{ with .Get "title" }} 
        <h5 class="card-title">
            {{ . }}
        </h5>
        {{ end }}

        <p class="card-text text-muted fs-6">
            {{ if eq $header "lorem-ipsum"}}
                Lorem Ipsum is simply dummy text of the printing and typesetting industry.
            {{ else if eq  $header "another-info" }}
                Contrary to popular belief, Lorem Ipsum is not simply random text.
            {{ else }}
                {{ with .Get "content" }} 
                    {{ . }}
                {{ end }}
            {{ end }}
        </p>
    </div>
</div>

You can put the above HTML file in the shortcodes folder under the layouts folder and please note it will replace the built-in figure shortcode in the Hugo.

If you want, you can modify the shortcode as per your requirments to add more details. The style classes in the components are from Bootstrap, but you can use as per you preferences.

For exploring more, you can checkout the Card shortcode here.


Read More