Hugo Shortcodes

Today I want to share my first glance at Hugo Shortcodes. In a previous article I described how to install Hugo. Content authoring is where I’ll spend most of my time with Hugo, so understanding the formatting options is important. This article will introduce two simple examples of formatting and arranging content in Hugo: traditional CSS, and Hugo shortcodes.

The traditional CSS approach

We can use CSS in Hugo sites as we would in any site:

  1. Launch a command prompt and type:

    cd C:\Hugo\Sites\mysitename\static
    mkdir css
    
  2. In this new directory create a file custom.css and add the following:

    .highlight_orange {
        color: #993300;
    }
    
  3. Then we need to reference the new CSS file in config.toml:

    [params]
    ...
    custom_css = ["css/custom.css"]
    ...
    
  4. Now within content pages we can use the following inline:

    <span class="highlight_orange">hello world</span>
    

    The resulting output will be:

    hello world

The Go approach (Shortcodes)

We can achieve the same result using Shortcodes. The Hugo documentation defines a shortcode as “a simple snippet inside a content file that Hugo will render using a predefined template”. Let’s check it out:

  1. In the command prompt navigate to the \layouts directory and create a new shortcodes folder:

    cd C:\Hugo\Sites\mysitename\layouts
    mkdir shortcodes
    
  2. In the shortcodes folder create a new file prehighlight.html and add the following:

    <span class="highlight_orange">{{ index .Params 0 }}</span>
    
  3. Now we can reference the shortcode in our content:

    {{% prehighlight "hello world" %}}
    

    Again, the resulting output should be:

    hello world

This example is, of course, not very useful, and CSS would probably suffice. However, the power of shortcodes is in creating more advanced, reusable snippets. For example links with target=\”_blank\”.