Hugo Snippets and Code Examples

, Updated by Julian Knight Reading time ~ 2 min.
Kb

A somewhat random collection of code for Hugo so that I don’t have to keep looking things up all over the Internet.

Index

Markdown oddities and extensions in Hugo

Hugo uses the Blackfriday markdown engine.

Some differences that you might want to be aware of:

  • GitHub Flavoured Most of the GitHub style markdown features are available. The default settings are a little more strict however (e.g. blank lines between heading and paragraph are required).

  • Nested Lists THere is a subtle bug in Blackfriday that it uses a logical tab spacing of 4 rather than the more normal (form markdown) 2. This means that nested content in a list has to be 1 tab or 4 spaces in, not 2 spaces which is the default for most versions of markdown libraries.

  • Alternative Rendering Engine It is possible to use the Mmark engine instead of Blackfriday. Put markup: mmark in a page frontmatter or name files *.mmark.

  • Header IDs Are enabled by default so each header gets an id. e.g.

      <h3 id="shortcode-to-render-a-code-example-in-a-page-post">Shortcode to render a code example in a page/post</h3>
        
  • Dashes By default, Latex style smart dashes are used. -- is an &ndash; – and --- is an &mdash; —. In addition, a single dash between words is translated to an &ndash; e.g. 12 June - 3 July becomes 12 June &ndash; 3 July

  • Syntax Highlighting triple backticks are used to wrap code blocks. Chroma is used for the highlighting.
    Alternatively, the older Pygments engine can be used.
    Use the {{ < highlight >}} markup form if you want to use extended controls such as line numbers, line highlights, etc.
    Configuration is done in config.toml, see the content-management/syntax-highlighting section of the docs for details.

The list of Highlight languages is given in the docs.

  • Definition Lists Are easily marked up as:

        Cat
        : Fluffy animal everyone likes
    
        Internet
        : Vector of transmission for pictures of cats \
        Don't forget the blank line between the terms
        : You can use multiple definition lines
        
  • Tables

        Name  | Age
        ------|------
        Bob   | 27
        Alice | 23
        
  • Footnotes

        This is a footnote.[^1]
    
        [^1]: the footnote text.
        
  • Strikethrough Uses 2 tildes ~~.

  • Trailing backslash Inserts a line break.

Many of these are optional, see the content-management/formats section of the Hugo docs for details.

Shortcode to render a code example in a page/post

layouts/shortcodes/render-code.html

{{ $file := .Get "file" | readFile }}
{{ $lang := .Get "language" }}
{{ (print "```" $lang "\n" $file "\n```") | markdownify }}

And in a post/page:

{{ % code file="/static/some-script.js" language="js" %}}

comments powered by Disqus