Skip to content

Instantly share code, notes, and snippets.

@gsong
Created February 29, 2012 04:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gsong/1937862 to your computer and use it in GitHub Desktop.
Save gsong/1937862 to your computer and use it in GitHub Desktop.
Liquid Gist tag for use in Jekyll
require 'cgi'
require 'open-uri'
# Require the ActiveSupport::Cache module
require 'active_support/cache'
module Fiftyfive
module Liquid
class GistTag < ::Liquid::Tag
def initialize(tag_name, gist_ref, tokens)
@gist_ref = gist_ref.strip
@gist_id, @filename = @gist_ref.split('/')
super
end
# A simple file-based cache in ./_tmp shared by all GistTag instances
def cache
@@cache ||= ActiveSupport::Cache::FileStore.new("_tmp/gist")
end
# Return from cache if possible; otherwise fetch and add it to cache
def fetch_gist(raw_gist_uri)
cache.fetch(raw_gist_uri) do
open(raw_gist_uri).read.chomp
end
end
def render(context)
raw_uri = "https://gist.github.com/raw/#{@gist_id}/#{@filename}"
script_uri = "https://gist.github.com/#{@gist_id}.js?file=#{@filename}"
<<MARKUP.strip
<div id="gist-#{@gist_ref.gsub(/[^a-z0-9]/i,'-')}">
<script src="#{script_uri}"></script>
<noscript>
<pre>#{CGI.escapeHTML(fetch_gist(raw_uri))}</pre>
</noscript>
</div>
MARKUP
end
end
end
end
Liquid::Template.register_tag('gist', Fiftyfive::Liquid::GistTag
<div>
<!-- For browsers that know JavaScript -->
<script src="https://gist.github.com/12345.js?file=abc.txt"></script>
<!-- For browsers or RSS readers that don't deal with JavaScript -->
<noscript>
<pre>
Raw content of a Gist file.
</pre>
</noscript>
</div>
<div id="gist-12345-abc-txt">
<script src="https://gist.github.com/12345.js?file=abc.txt"></script>
<noscript>
<pre>Raw content of a Gist file.</pre>
</noscript>
</div>
require 'cgi'
require 'open-uri'
module Fiftyfive
module Liquid
class GistTag < ::Liquid::Tag
def initialize(tag_name, gist_ref, tokens)
@gist_ref = gist_ref.strip
# gist_ref is in the form of `gist_id` or `gist_id/filename`
@gist_id, @filename = @gist_ref.split('/')
super
end
def render(context)
raw_uri = "https://gist.github.com/raw/#{@gist_id}/#{@filename}"
script_uri = "https://gist.github.com/#{@gist_id}.js?file=#{@filename}"
<<MARKUP.strip
<div id="gist-#{@gist_ref.gsub(/[^a-z0-9]/i,'-')}">
<script src="#{script_uri}"></script>
<noscript>
<pre>#{CGI.escapeHTML(open(raw_gist_uri).read.chomp)}</pre>
</noscript>
</div>
MARKUP
end
end
end
end
Liquid::Template.register_tag('gist', Fiftyfive::Liquid::GistTag)
@gsong
Copy link
Author

gsong commented Mar 1, 2012

@vdurmont
Copy link

vdurmont commented Jan 6, 2014

Awesome, thanks for this gist for gists :)

(FYI, you missed a closing parenthesis in gist.rb)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment