Get updates via: rss | twitter | email | google+

Embed code files into Jekyll posts ala gist

Written by Guillermo Garron .
Date: 2013-06-08 13:22:35 -0400

I have finally decided to start learning Ruby, and actually learn to code. I know this is going to be hard, as I am 40 years old already and I know is harder now than when I was 20.

As a child I have seen some Basic programming language, and later a few of C++, where I learn a little about sub-routines and classes. I have been reading about Ruby, and it seems not to easy.

Considering I am going to learn fast, and that I will be sharing some small and simple snippets of code in this blog, I wanted to prepare the blog for that.

“All the cool guys use gists today”. Well, maybe I am not so cool, or maybe because of I do not like the cloud, I am not going to use gists to share my code.

What I want is to put my code files in a special folder inside the structure of Jekyll, and from there embed its content into blog posts. I have been looking for some plugin that already does that. I could not find such a plugin, but I have found this one. Modifying the code a little, I have ended with this:

require 'cgi'

module Fiftyfive
  module Liquid
    class EmbedCode < ::Liquid::Tag
      def initialize(tag_name, filename, tokens)
        @filename = filename.strip
        @codefile = "_code/#{@filename}"
      # get the file
      def fetch_file(raw_text)
      # Render the code into html tags
      def render(context)
        mycode = "#{@codefile}"

Liquid::Template.register_tag('gist', Fiftyfive::Liquid::EmbedCode)

This is how it works.

You are done, the contents of that file is going to be embedded into the Jekyll post between <pre><code></code></pre> html tags.

Hope this may be useful to someone


If you enjoyed the article, please share it

twitter | facebook | google+ | linkedin | email | reddit