Highlighting Lines in Hugo Code Snippets

Hugo makes it quite simple to share code snippets with syntax highlighting on your site, but did you know you can highlight individual lines in code-snippets as well?

Note: Recent Hugo versions use a syntax highlighting engine called Chroma, whereas older Hugo versions used Pygments. However, whether you are using Chroma or Pygments, this feature still works.

When using markdown, the default/simplest approach for highlighting code is simply to use a fenced code block:

1``` kotlin
2class Person {
3  var name: String = ""
4  var age: Int = 0
5
6  fun component1() = name
7  fun component2() = age
8}
9```

This results in clean highlighted code with a minimum of ceremony.

1class Person {
2  var name: String = ""
3  var age: Int = 0
4
5  fun component1() = name
6  fun component2() = age
7}

However, these code fences only support language parameterization. Hugo also allows you to get to more specific features of the highlighter by using the “highlight” shortcode. Specifically, you can request that individual lines be highlighted:

1{{< highlight kotlin "hl_lines=5-6" >}}
2class Person {
3  var name: String = ""
4  var age: Int = 0
5
6  fun component1() = name
7  fun component2() = age
8}
9{{< /highlight >}}

This new syntax results in pretty line highlights targeting a code section of interest:

1class Person {
2  var name: String = ""
3  var age: Int = 0
4
5  fun component1() = name
6  fun component2() = age
7}

hugo 
comments powered by Disqus