DEV Community

Shekhar Chandra
Shekhar Chandra

Posted on

Hugo Shortcodes to Embed Anything

Introduction

Hugo is a static site generator suitable for personal websites and blogs. Being an open source project it lets users to manipulate the presentation layer to great extent. Strong theme support and customization options makes it a perfect platform to host almost any kind of web object.

Shortcodes

Hugo shortcodes lets developers embed any snippet into a markdown article. It comes with a lot of in built shortcodes to embed widgets from most popular sharing platforms. Shortcodes can embed a complete HTML document as well not just script tags and small snippets. This makes it possible to natively embed a small standalone project.

Shortcodes are html files which are, by convention, placed in /layouts/shortcodes directory. Once placed the shortcode can be included in any page using {{\< filename \>}}

Passing argument

It is possible to pass arguments while including a shortcode. Just add any number of positional arguments like in a command line and hugo will capture them as string on rendering.

For example, the first argument can be captured as a zeroth positional argument inside the shortcode file.

{{- $arg0 := .Get "arg0" | default (.Get 0) -}}
Enter fullscreen mode Exit fullscreen mode

and can be accessed anywhere in the html document as such

<a href={{ $arg0 }}></a>
Enter fullscreen mode Exit fullscreen mode

Adding Style

Shortcodes get the style definition from the selected theme of custom css. A shortcode specific CSS can be included in the HTML as usual and place in /static/ folder

JavaScript and Minification

The generated HTML gets minified naturally while compiling for production using --minify option. To make sure the javascript used in the shortcode is minified as well, place them in the /assets folder and include using hugo minification pipe.

    {{ $customjs := resources.Get "/custom.js" | resources.Minify }}
    <script src="{{ $customjs.Permalink }}"></script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)