Including Github Repo Code in Jekyll
Including code references in technical blogs is important to explain and demonstrate coding concepts. The typical way to do this is to embed Gists into your posts. However, I am writing several posts that all reference a public Github repo, not snippets that are inside Gists. Also, being able to reference code in a larger code base can help provide additional context if necessary. Taking inspiration from an existing Liquid Gist Tag, I created the Github Sample Tag.
The Github Sample Tag is a Jekyll tag that allows bloggers to include a sample of a file hosted on Github. Here is an example of it in use:
1 def determine_line_numbers(first, last)
2 if first.nil? && last.nil?
3 first = 0
4 last = -1
5 elsif last.nil?
6 last = first
7 end
8
9 [first.to_i, last.to_i]
10 end
This example is actually 3 different tags in play, two from Github Sample Tag and one built-in. The first is the github_sample
tag, which on it’s own just retrieves a portion of a raw Github file:
def determine_line_numbers(first, last) if first.nil? && last.nil? first = 0 last = -1 elsif last.nil? last = first end [first.to_i, last.to_i] end
The second is the builtin highlight
block with the appropriate language format set:
1 def determine_line_numbers(first, last)
2 if first.nil? && last.nil?
3 first = 0
4 last = -1
5 elsif last.nil?
6 last = first
7 end
8
9 [first.to_i, last.to_i]
10 end
The third piece is the github_sample_ref
tag, which can be used on it’s own like so:
All three work well together and I can use a Github Sample from Jekyll Github Sample README file of the syntax:
{% github_sample_ref /bwillis/versioncake/989237901cb873f96df12be48cbf1239be496bd7/Appraisals %}
{% highlight ruby %}
{% github_sample /bwillis/versioncake/989237901cb873f96df12be48cbf1239be496bd7/Appraisals 0 5 %}
{% endhighlight %}
Please leave questions and comments in the repo issues.