Hugo Tips, Shortcodes, and Fragments

Hugo is the static site generator that I use to build the new parts of the Infinite Ink website, including this page. I use the fragments below in some of Infinite Ink’s source files.

Page contents

News

2020-October  Updated fragment 13 so it now includes information about commenting out Hugo shortcodes.

2020-August  Significant updates in this article, including creating the sections ️Dates in Hugo📆, ️Variable names in Hugo, and Hugo docs shortcodes. And changed the title from Hugo Tips and Fragments to Hugo Tips, Shortcodes, and Fragments.

 

Commenting in website source files

Commenting is useful for writing notes to yourself and for holding fragments that you have used in the past or may use in the future. To learn about the comment syntax of many languages, see Infinite Ink’s Commenting Code Cheatsheet.

In a child block layout file, do not put a comment — or anything other than blank lines — outside a define-end container:

only blank lines here

{{ define "main" }}

Go Template code and comments here

{{ end }}

only blank lines here

 

1. Commenting out executable code

In the Go Template language, which is also known as Go HTML, you can comment out[1] executable code with the following single- or multi-line comment syntax.

{{/* Go HTML single-line comment */}}


{{/*

Go HTML
multi-line
comment

*/}}

The following also work.

{{- /* Go HTML single-line comment */ -}}


{{- /*

Go HTML
multi-line
comment

*/ -}}

Note that in this second style of Go Template comment syntax, a space is required between each dash (-)[2] and its corresponding slash (/).

To learn about commenting out Hugo shortcodes, see 13. Escaping and commenting out Hugo shortcodes below.

 

2. Commenting out notes and non-executable code

In a layout file or a Markdown content file, you can comment out text (such as an English-language note to yourself) or non-executable code with the following single- or multi-line comment syntax.

<!--  HTML or Markdown single-line comment -->

<!--

HTML or Markdown
multi-line
comment

-->
Do not use these HTML-style comments to comment out Go Template code in a Hugo layout file. If you do, Hugo will process the code and potentially generate error messages or change the layout logic.

One-off custom shortcodes

Hugo shortcodes are a way to use Go Template code within a content file. Reusable and one-off shortcodes usually live in the layouts/shortcodes/ directory but, starting with Hugo v0.52, you have the option to put a shortcode directly into a content file by using an “inline shortcode.” This is especially useful for one-off shortcodes such as the ones discussed in fragment 3 and fragment 4 below.

To use inline shortcodes you need to set enableInlineShortcodes to true in your Hugo config file by putting this in your config.yaml:

enableInlineShortcodes: true

Or this in your config.toml:

enableInlineShortcodes = true

 

3. “Writing In Progress” inline shortcode

On Infinite Ink’s To-Do and Done Lists, in the section Writing In Progress, there is a list of articles that have not yet been published. For production — i.e. what you see — this is a list of titles without links, but for me, when I am developing the Infinite Ink website with the hugo server command, this is a list of titles with links to these unreleased articles. I do this by putting my writing-in-progress articles in a directory named content/wip/[3][4] and by putting the following inline shortcode in Infinite Ink’s website-todo-done.asciidoc[5] content file.

{{< wip.inline >}}
<ul>
  {{ range (where .Site.RegularPages.ByTitle "Section" "eq" "wip") }}
  <li>
    {{ if hugo.IsProduction }}
      <em>{{ .Title }}</em>
    {{ else }}  <!-- not production -->
      <a href="{{ .RelPermalink }}"><em>{{ .Title }}</em></a>
    {{ end }}  <!-- end if-else -->
  </li>
  {{ end }}  <!-- end range -->
</ul>
{{< /wip.inline >}}

 

💡

In the highlighted line above…

  • the parentheses surrounding the where clause are not needed, but I like to use them because it reminds me that the syntax of the Go HTML range function is range COLLECTION.

  • And the "eq" in the phrase "Section" "eq" "wip" is not needed because it is the default operator in a where clause. I like to specify it anyway as a note to self about the general syntax of the Go HTML where function.

 

I do things to ensure that no WIP[3] article is mentioned anywhere on Infinite Ink other than Infinite Ink’s To-Do and Done Lists. For example, I specify appropriate build options and the tag list in a WIP article’s front matter is commented out until it is no longer a WIP.

 

4. “Hugo version” inline shortcode

Infinite Ink’s I Use This (https://www.ii.com/uses/) page displays this list item:

  • hugo v0.80.0/extended

Each time hugo builds the Infinite Ink site, the part after “hugo ” is generated by the following fragment in Infinite Ink’s uses.asciidoc[5] content file.

v{{< hv.inline >}}
  {{- hugo.Version -}}
{{< /hv.inline >}}/extended

 

The dashes[2] in the delimiters {{-  and  -}} tell hugo to trim whitespace around the output of hugo.Version. These trim-whitespace delimiters must be specified exactly like this, i.e.:

  • a trailing space in the left delimiter,

  • a leading space in the right delimiter,

  • and no whitespace between either curly bracket and its dash.

Reusable custom shortcodes

The shortcodes in this section reside in my layouts/shortcodes/ directory and can be called from any content file by using the syntax specified in the comment at the top of the shortcode.

5. build-date

{{/*

USAGE:

  {{< build-date >}}

Path: layouts/shortcodes/build-date.html
Purpose: display current date

*/}}

{{- now.Format "2006-01-02" -}}

Here it is in action…

page built 2021-01-14
           ----------
               👆
           generated by build-date shortcode

This build-date shortcode is used in the following Infinite Ink articles.

 

️Dates in Hugo📆

The string 2006-01-02 in the above build-date shortcode specifies the date format. Note that 2006, 01, and 02 are not a random year, month, and day. Instead they come from the Go reference date, which is Jan 2 15:04:05 2006 MST.

You can remember the reference date with the following mnemonic.

Jan 2 15:04:05 2006 MST
  1 2  3  4  5    6  -7

To learn about this, see:

 

6. omnicomment

{{/*

Usage syntax:

    {{< omnicomment >}}
        commented
        out
    {{< /omnicomment >}}

Forked from: github.com/gohugoio/hugoDocs/blob/master/layouts/shortcodes/todo.html
Path: layouts/shortcodes/omnicomment.html
Purpose: comment in content file written in any markup language Hugo supports
Why 1: no comment translation needed when change file from, e.g., .md to .adoc
Why 2: comment out big chunk that contains multiple markup comments[6]

*/}}

{{ if .Inner }}{{ end }}

Note that this is a no-op shortcode.

 

7. years-since and years-since-phrase

{{/*

USAGE:

  {{< years-since YYYY >}}

EXAMPLE:

  {{< years-since 2009 >}}

Path: layouts/shortcodes/years-since.html
Why: as time goes on, this will still be the approximate number of years since YYYY

*/}}

{{ $thisyear := int (now.Format "2006") }}
{{ $thatyear := .Get 0 }}

{{- sub $thisyear $thatyear -}}

The above years-since shortcode returns leading whitespace so I actually use the below years-since-phrase shortcode.

 ❓ 

If you know how to remove that leading whitespace, please comment at the bottom of this page. I’ve tried a lot of things, including Hugo’s replaceRE and trim functions.

 

{{/*

USAGE:

  {{< years-since-phrase YYYY >}}

EXAMPLE:

  {{< years-since-phrase 2009 >}}

Path: layouts/shortcodes/years-since-phrase.html
Why: as time goes on, this phrase will still be approximately true

*/}}

{{ $thisyear := int (now.Format "2006") }}
{{ $thatyear := .Get 0 }}

{{ $difference := sub $thisyear $thatyear }}

(~{{- $difference }} years ago).

This years-since-phrase shortcode is used in the following Infinite Ink articles.

 

️Variable names in Hugo

The names of Hugo variables (including parameter keys in config files and front matter)…

  • cannot contain a dash character (-),[2]

  • can contain underscores (_) and alphanumeric characters,

  • and are sometimes case sensitive.

Variable names that a Hugo user creates in a layout file — such as $thisyear, $thatyear, and $difference — are called custom variables and must start with a dollar sign ($).

💡
Bep, Hugo’s lead developer, recommends all lower case snake_case — for example $this_year and $that_year — for custom variable names. For more about this, see discourse.gohugo.io’s Best practices for naming variables etc.

 

8. get-leaf-text

{{- /*

USAGE:

  {{< get-leaf-text filename >}}

EXAMPLE:

  {{< get-leaf-text config.py >}}

Path: layouts/shortcodes/get-leaf-text.html
Purpose: get content of text file located in current leaf bundle

*/ -}}

{{- $filename := .Get 0 -}}
{{- $file := .Page.Resources.GetMatch $filename -}}
{{- $file.Content -}}

This get-leaf-text shortcode is used in the source of Infinite Ink’s qutebrowser’s Template config.py like this:

{{< highlight python >}}
{{< get-leaf-text config.py >}}
{{< /highlight >}}

And in the source of Infinite Ink’s Intertwingling AsciiDoc and Hugo⁠ like this:

{{< highlight yaml "hl_lines=4 8" >}}
{{< get-leaf-text markupdotasciidocext.yaml >}}
{{< /highlight >}}

The highlight shortcode is discussed in fragment 11 below.

 

9. html4-get-bundle-image🖼️

{{/*

USAGE:

{{< html4-get-bundle-image "filename" "alt text" "width" "link" >}}

NOTE: parameters 1 & 2 required, parameters 3 & 4 optional

EXAMPLE 1:
{{< html4-get-bundle-image "gologo.png" "Go Logo" >}}

EXAMPLE 2:
{{< html4-get-bundle-image "gologo.png" "Go Logo" "50%" >}}

EXAMPLE 3:
{{< html4-get-bundle-image "gologo.png" "Go Logo" "25%" "https://blog.golang.org/go-brand" >}}

PATH: layouts/shortcodes/html4-get-bundle-image.html

PURPOSE: get image located in current bundle

*/}}


{{ $filename := .Get 0 }}
{{ $alt := .Get 1 }}
{{ $width := .Get 2 }}
{{ $link := .Get 3 }}

{{ $file := .Page.Resources.GetMatch $filename }}


{{ with $link }}
<a href="{{ . }}">
{{ end }}
<img
  src="{{ $file.RelPermalink }}"
  alt="{{ $alt }}"
  {{ with $width }} width="{{ . }}" {{ end }}
>
{{ if $link }}
</a>
{{ end }}

 

Here are three examples…

Example 1: Unspecified width

Shortcode call
{{< html4-get-bundle-image "gologo.png" "Go Logo" >}}
Go Logo

Example 2: 50% width

Shortcode call
{{< html4-get-bundle-image "gologo.png" "Go Logo" "50%" >}}
Go Logo

Example 3: 25% width and linked

Shortcode call
{{< html4-get-bundle-image "gologo.png" "Go Logo" "25%" "https://blog.golang.org/go-brand" >}}
Go Logo

 

HTML4 images vs HTML5 images

  • In both HTML4 and HTML5, it is valid to use alt="" as an img attribute, but you should do this only if an image is for decoration and is not important to the meaning of a web page. For example, the images on Infinite Ink’s #gohugo Portal and #golang Portal are specified with alt="" because they are just for decoration.

 

10. embed-twitter-list

{{/*

USAGE:

  {{% embed-twitter-list listname %}}

EXAMPLE:

  {{% embed-twitter-list zeitgeist %}}

Path: layouts/shortcodes/embed-twitter-list.adoc
Purpose: Embed heading and Twitter list in a page written in AsciiDoc

*/}}


{{ $listbasename := .Get 0 }}

=== @nm/lists/{{- $listbasename }}

++++
<a class="twitter-timeline" href="https://twitter.com/nm/lists/{{- $listbasename -}}?ref_src=twsrc%5Etfw">A Twitter List by @nm <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
++++

This shortcode is used in some Infinite Ink portals, for example in the #zeitgeist Portal.

This shortcode uses AsciiDoc syntax and is meant to be used in an AsciiDoc (.ad, .adoc, or .asciidoc) content source file and called with the {{% and %}} shortcode delimiters (not the {{< and >}} shortcode delimiters).

 

Built-in shortcodes

Hugo includes built-in shortcodes, which you can read about at:

A good way to learn about writing your own shortcodes is to look at the source code of Hugo’s built-in shortcodes. This code is available on GitHub at:

 

11. highlight

When I use Hugo’s built-in highlight shortcode and want to highlight lines, I almost always need to look up the syntax, which can look like this:

{{< highlight html "hl_lines=3-5" >}}

html code that will be rendered with lines 3, 4, and 5 highlighted

{{< /highlight >}}

Or this:

{{< highlight toml "hl_lines=1 12 33" >}}

toml code that will be rendered with lines 1, 12, and 33 highlighted

{{< /highlight >}}

To learn about the highlight shortcode, see:

 

💡
To view a list of all possible highlighting languages, such as html and toml, see gohugo.io/content-management/syntax-highlighting#list-of-chroma-highlighting-languages.

 

Hugo docs shortcodes

More shortcodes, including admonition shortcodes, are available in the Hugo Documentation repository in this directory:

To use one of the Hugo docs shortcodes, copy it to somewhere below your project’s layout/shortcodes/ directory, for example to one of the following directories.

layout/shortcodes/
layout/shortcodes/3rdparty/
layout/shortcodes/hugodocs/
💡

The Hugo docs note, tip, and warning admonition shortcodes start with the following line.

{{ $_hugo_config := `{ "version": 1 }` }}

This tells Hugo to process this shortcode the way that Hugo v0.54.0 and earlier do. To learn about this, see the Hugo v0.55.0 release notes.

 

Escaping strings in content files from Hugo processing

12. Escaping emoji codes

In step 13.2.2. Include emoji codes in Infinite Ink’s Hugo Tutorial, I wrote about the following emoji codes.

:man_astronaut:
:star:
:woman_astronaut:
:bulb:
:wrench:
:sparkles:

Since I have enableEmoji: true in my config.yaml, Hugo emojifies the above strings in a content file to:

👨‍🚀
⭐
👩‍🚀
💡
🔧
✨

So how do you write about these strings without Hugo emojifying them? There is more than one way to escape emoji codes. The way I do it is to use an HTML entity for one of the colons in each emoji code. For example:

:man_astronaut&#58;
:star&#58;
:woman_astronaut&#58;
:bulb&#58;
:wrench&#58;
:sparkles&#58;

This trick works…

  • in some parts of a Markdown content file, but does not work in Markdown inline code or in a Markdown code block

  • throughout an AsciiDoc content file, but sometimes needs [subs="replacements"]

 

13. Escaping and commenting out Hugo shortcodes

In a Hugo content file, shortcodes are called using either the delimiters {{< and >}} or the delimiters {{% and %}}.

13.1. Escaping shortcodes

If you want to write about shortcodes, as I did in fragments 3, 4, 5, 6, 7, 8, 9, 10 and 11 above, you need to escape these strings from being interpreted as being part of actual shortcode calls. Hugo uses the following syntax to escape these delimiters in a content source file:

{{</* something */>}}

{{%/* something */%}}

If you use the above delimiters in a content file, they will be rendered in the destination file as:

{{< something >}}

{{% something %}}

And these strings will not be interpreted as shortcode calls.

 

I learned about escaping Hugo shortcodes in the discourse.gohugo.io thread How is the Hugo Doc site showing shortcodes in code blocks?

 

️13.2. Commenting out shortcodes in Markdown

To comment out a shortcode in a Markdown (.markdown, .md, or .mdown) content source file, you can do this:

<!--
{ {< shortcode call >}}
-->

Notice the space between the two leading curly braces. Actually any character between the curly braces will denature the shortcode. For example, I like to use an exclamation mark because it is more noticeable than a space character:

<!--
{!{< shortcode call >}}
-->

 

️13.3. Commenting out shortcodes in AsciiDoc

To comment out a shortcode in an AsciiDoc (.ad, .adoc, or .asciidoc) content source file, you can do this:

////
{!{< shortcode call >}}
////

Or this:

// {!{< shortcode call >}}

 

💡
If you really want it to be noticeable that a shortcode is commented out, you could use !!! rather than ! to denature a shortcode call.

 

Hugo configuration

To learn about configuring Hugo, see gohugo.io/getting-started/configuration/.

14. frontmatter

I use the following nested map, which is also known as a table,⁠[8] in my config.yaml because…

  1. I want date and publishDate to mean the same thing and

  2. if no date is specified, I want a reasonably sane date (:fileModTime) to be used rather than Hugo’s default date, which is 0001-Jaunary-01.

frontmatter:
  date: 
    - publishDate
    - :filename
    - date
    - :fileModTime
  publishDate: 
    - publishDate
    - :filename
    - date
    - :fileModTime
  lastmod: 
    - lastmod
    - :fileModTime

 

For more about this, see Stackoverflow.com’s Hugo Date vs PublishDate, which includes a post by n m (i.e. me😄).

The TOML syntax for this table is in fragment 16 below.

 

15. markup

Starting with Hugo v0.60.0[9], the way to override Hugo’s default markup settings is to use a markup nested map in your project’s config file. Here is an excerpt of Infinite Ink’s config.yaml:

markup:
  goldmark:
    renderer:
      unsafe: true  # default is false
  highlight:
    style: tango    # default is monokai

 

Note that…

  • Without the unsafe: true setting, which is the highlighted line in this YAML fragment, raw HTML in a Goldmark-flavored Markdown source file will be replaced with <!-- raw HTML omitted --> in the markdownified[10] destination file.

  • A nested-map markup setting like this does not work in the front matter of a content file. These variables must be set globally.

  • The colors and italics in this YAML fragment are thanks to tango-style syntax highlighting.

 

💡

To view examples of all possible values of markup.highlight.style, including monokai and tango, see the Chroma Style Gallery at xyproto.github.io/splash/docs/all.html.

 

For more about this, see the following.

 

The TOML syntax for this markup nested map, which is also known as a table, is at the bottom of the next fragment.

 

16. Dividing lines for config.toml

When I use a config.toml, I like to include comments like the three highlighted lines below.

### ---> Put tables below non-tables <--- ###


# next from “One-off shortcodes” above
enableInlineShortcodes = true


# next from fragment 12 above
enableEmoji = true 


### ---> Put TOML tables below here <--- ###


# next from fragment 14 above
[frontmatter]
  date = ["publishDate", ":filename", "date", ":fileModTime"]
  publishDate = ["publishDate", ":filename", "date", ":fileModTime"]
  lastmod = ["lastmod", ":fileModTime"]


# next from fragment 15 above
[markup]

  [markup.goldmark]
    [markup.goldmark.renderer]
      unsafe = true

  [markup.highlight]
    style = "tango"


### ---> Put tables below non-tables <--- ###

 

I use these triple-hash comments because I have spent a lot of time debugging Hugo websites when I, for example, put a non-table at the bottom of a config.toml.⁠😩

To learn about TOML, which is an alternative to YAML, see:

Comments 👍 👎 📝

To comment, you must be signed in to GitHub.

Endnotes


2. The Unicode name for the “dash” character (-) is “hyphen-minus,” but its proper name is rarely used. Instead it is usually referred to as “dash,” “hyphen,” or “minus.” Details are at Hyphen-minus - Wikipedia.
3. WIP can mean “work in progress” or “writing in progress.”
4. The front matter of some of Infinite Ink’s WIP articles include draft: true. Only the titles of the WIP articles that are not drafts are listed when I publish Infinite Ink’s To-Do and Done Lists page.
6. By “multiple markup comments,” I mean markup comments that are not omnicomments. This gets around the problem of trying to nest markup comments, which does not work (because the first close-comment markup tag will end the outermost open-comment markup tag).
7. Another example of a shortcode and function having the same name: the relref shortcode and relref function.
8. A nested map is also known as an associative array, a dictionary, a dict, a hash table, a hash, a map, a mapping, a named map, an object, or a table. For more about this data-serialization object, see Infinite Ink’s YAML includes Atoms, Maps, and Lists.
9. As of Hugo v0.60.0, which was released on 2019-November-27, Goldmark is the default Markdown parser, the Mmark Markdown parser is deprecated, and it was announced that the Blackfriday Markdown parser will eventually be deprecated.
10. In Hugo markdownify means convert Markdown to HTML