How to highlight code on a Jekyll site - Syntax Highlighting

February 11, 2019  1 minute read  

To have code snippets highlighted so that they are more reader-friendly, we have to wrap our code using the following syntax.

1 Jekyll Rouge Highlight Tag

You can install kramdown markdown parser and rouge highlighter - Jekyll’s default highlighter using the following command:

gem install kramdown rouge

After installing kramdown and rouge, you can add the following to your _config.yml file.

markdown: kramdown
highlighter: rouge
    input: GFM

After that, you can now highlight your code by surrounding your code with {% highlight language %} and {% endhighlight %}. Replace languageCode with the code language. You can refer to this rouge doc for the list of supported languages.

Example:


{% highlight javascript %}
function sayHello(name) {
  if (!name) {
    console.log('Hello World');
  } else {
    console.log(`Hello ${name}`);
  }  
}  
{% endhighlight %}

You can read liquid tags doc for more detailed information.

2 GitHub Flavored Markdown Fenced Code Blocks

We can also use GitHub Fenced Code Blocks syntax. This syntax seems to be less verbose and cleaner.

Example:

```
function sayHello(name) {
  if (!name) {
    console.log('Hello World');
  } else {
    console.log(`Hello ${name}`);
  }
}

```

To syntax highlight for code of a specific language, you can add the language name next to the opening 3 backticks. You can refer to this rouge doc for the list of supported languages.

Example with language specified:

```javascript
function sayHello(name) {
  if (!name) {
    console.log('Hello World');
  } else {
    console.log(`Hello ${name}`);
  }
}
```

Result

function sayHello(name) {
  if (!name) {
    console.log('Hello World');
  } else {
    console.log(`Hello ${name}`);
  }
}

References:

  1. GitHub Syntax Highlighting Doc
  2. GitHub Creating and Highlighting Code Blocks Doc

Support Jun

Thank you for reading!    Support JunSupport Jun

Support Jun on Amazon US

Support Jun on Amazon Canada

If you are preparing for Software Engineer interviews, I suggest Elements of Programming Interviews in Java for algorithm practice. Good luck!

You can also support me by following me on Medium or Twitter.

Feel free to contact me if you have any questions.

Tags:

Categories:

Updated:

Comments