I use Jekyll for this blog and needed to find ways to add code snippets to it. It required quite a bit of searching though, and the default preferences aren’t my favorite. Here’s how I tweaked mine.
Enable Rouge highlighting
Github pages
uses Jekyll
version 3.
That means
Rouge
need not be separately installed.
You can just configure it in the _config.yml
file by adding or editing the following parameters.
1
2
markdown: kramdown
highlighter: rouge
Add syntax CSS to the project
Dmitri Moore has created this great
CSS file
that can be added to the css folder of the project.
Don't forget to add the following line within the
head
tag of the project.
1
<link href="/css/syntax.css" rel="stylesheet">
I also added his adjustments for better line numbers to the end of the file.
Customize the syntax CSS file
I wanted to make the code snippets match the rest of my blog. So I also added the following minor adjustments:
1
2
3
4
5
6
7
.highlight {
background: rgb(230, 230, 230);
max-height: 300px;
overflow: scroll;
border: 1px #C1C1C1;
border-radius: 3px;
}
Add code blocks to your posts
The previous steps allow for code blocks to be written. This can be done by adding the following:
1
2
3
4
5
{% highlight html linenos %}
// your code here
{% endhighlight %}
You can change
html
to any of the many languages listed
here.
Sometimes, you may have to explain something in Angular or Jekyll itself. You don’t want Jekyll to interpret the written lines as code. The solution is to wrap the code in a raw block
1
2
3
4
5
{% raw %}
// your code here
{% endraw %}
Side note:
Schabse Laks
has a good suggestion on writing the endraw
ta itselfg.
It can get tricky because attempting to use the raw
tag on it simply terminates the block and causes an error.
He uses a liquid variable for the {%
section of the endraw
tag.
Add inline code styling
In my blog posts, I also occassionally need to add inline code that look like
this
.
For that, I simply use the
code
tag.
Like the code blocks, I wanted this to match my blog's theme.
So I also added very similar CSS.
1
2
3
4
5
6
code {
background-color: rgb(230, 230, 230);
border: 1px solid #C1C1C1;
border-radius: 3px;
padding: 2px;
}
These are the steps I've taken to display readable code on my blog. Some of the steps I've taken are based on other people's blogs and discoveries . Hope this list is a useful curation of good references on the subject.