That's a good question. Here is my two cents.
Here, I took the example of your _posts/2012-11-16-idisposable.html
post.
Storing code snippets
As code is part of the post's content I logically move it to the _posts
folder. Storing it in the _includes
folder is not so good as this is a template folder.
Let's copy the idisposable/TryFinallyDispose.cs.html
from _includes/code-snippets
to _posts/_code
or anything you want.
As the code is stored in an underscored folder (_code), it will not be processed as is by Jekyll. We will just 'include' it in our posts.
Note : code snippet can be saved as code.cs
As we will use highligting from Jekyll dependancies (see below), we just rework code snippet by, removing <pre>
and <code>
.
It becomes :
var x = new X(); // X is a class that implements IDisposable
try
{
// do something with x
}
finally
{
x.Dispose();
}
Displaying code
Jekyll offers various ways to highlight code (markdown
, pygments
, rouge
, ..). Here I demonstrate the pygments
way, but it's up to you to explore other solutions.
The base template will be (_includes/code-snippet-csharp.html
):
{% capture filePath %}_code/{{include.file}}{% endcapture %}
{% highlight csharp %}
{% include_relative {{filePath}} %}
{% endhighlight %}
note: one drawback here, in the {% highlight csharp %}
, code name is hardcoded. I found no way to pass the language
to the highlight
tag as a variable. If you want to use multiple languages, you'll need to duplicate the include template as code-snippet-csharp.html
, code-snippet-js.html
, ...
Styling code
In order to beautify our code, we need an extra css file. The basic one is here, but there is many more.
Style is saved as assets/syntax.css
and included in _layouts/default.hmtl
:
<link rel="stylesheet" href="{{site.baseUrl}}assets/syntax.css">
And it can also be included in your sass process.
Including code in posts
We now just have to call our code in _posts/2012-11-16-idisposable.html
.
{% include code-snippets/idisposable/TryFinallyDispose.cs.html %}
Is replaced by :
{% include code-snippet-csharp.html file="idisposable/TryFinallyDispose.cs.html" %}
Result
Better content structure and a nicely highlighted code !
{% highlight %}
tags. – Rudy Velthuis