How to highlight code on a Jekyll site - Syntax Highlighting
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:
Support Jun
Thank you for reading! Support Jun
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.
Comments