Syntax highlighting in Hugo


The back-ticks ` or ``` are used to keep original text formatting within Hugo rendered pages.

Example 1, single back-tick:

A single back-tick at the start and end of the line

Example 2, triple back-tick:

Three back-ticks above and three back-ticks below this line

Using back-ticks for code keeps the formatting, but the output is not pretty or easy to read:

def fix_hostname(hostname):
    hostname = re.sub(r'[\\/:"*?<>|]+', "-", hostname)
    hostname = hostname.lower()
    return hostname

hostname = fix_hostname(device["name"])

In Hugo, the highlight short-code is used for syntax highlighting. Wrap the code with the following lines:

{{< highlight python  "linenos=table" >}}

{{< / highlight >}}

It will look like this in the markdown file:

{{< highlight python  "linenos=table" >}}
def fix_hostname(hostname):
    hostname = re.sub(r'[\\/:"*?<>|]+', "-", hostname)
    hostname = hostname.lower()
    return hostname

hostname = fix_hostname(device["name"])
{{< / highlight >}}

Which results in this:

1
2
3
4
5
6
def fix_hostname(hostname):
    hostname = re.sub(r'[\\/:"*?<>|]+', "-", hostname)
    hostname = hostname.lower()
    return hostname

hostname = fix_hostname(device["name"])
`

On a side note, to display unprocessed short-codes, put a /* */ between the curly brackets:

{{< /* highlight python  "linenos=table" */ >}}