Skip to content

Instantly share code, notes, and snippets.

@panoply
Last active December 16, 2019 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panoply/2cd52140ca468bfea986c6b723ca760d to your computer and use it in GitHub Desktop.
Save panoply/2cd52140ca468bfea986c6b723ca760d to your computer and use it in GitHub Desktop.
Jekyll SVG icons and sprite
module Jekyll
module Tags
class IconTag < Liquid::Tag
def initialize(tag_name, markup, tokens)
@markup = markup
super
end
def render(context)
# Gather settings
site = context.registers[:site]
markup = Liquid::Template.parse(@markup).render(context)
# Extract icon name
@dir = File.expand_path(site.config["icons_dir"]).freeze
@name = markup.match(/(?<=['"])[\w\-]+(?=['"]\s+)/)
@icon = "#{@name}.svg"
# Attributes object reference
attributes = {}
markup.scan(Liquid::TagAttributes) do |key, value|
attributes[key] = value
end
# Class attribute
@class = attributes["class"]
unless @class.nil?
svg_class = @class.gsub!(/\A["']|["']\Z/, "")
svg_class = "#{svg_class}"
end
@role = attributes["role"]
unless @role.nil?
svg_role = @role.gsub!(/\A["']|["']\Z/, "")
svg_role = "role=\"#{svg_role}\""
else
svg_label = "role=\"img\""
end
@sprite = File.join(@input, @icon)
if @icon === "sprite.svg"
svg_dir = File.join(@output, "sprite.svg")
svg_tag = File.read(svg_dir, site.file_read_opts)
elsif File.exists?(@sprites)
svg_tag = "<svg role=\"img\" #{svg_label} class\=\""
svg_tag += svg_class ? "#{svg_class}\">" : "icon-#{@name} \">"
svg_tag += "<use xlink:href\=\"\##{@name}\"></use>"
svg_tag += "</svg>"
elsif File.exists?(@inline)
svg_dir = File.join(@output, "inline", @icon)
svg_tag = File.read(svg_dir, site.file_read_opts)
svg_tag = svg_tag.gsub!(/<svg/, "<svg #{svg_role} class=\"icon-#{@name}\"")
unless svg_class.nil?
if svg_tag.match(/class\=/)
svg_tag = svg_tag.gsub!(/class\="[^"]+\"/, "class\=\"#{svg_class}")
else
svg_tag = svg_tag.gsub!(/<svg/, "<svg class\=\"#{svg_class}\"")
end
end
end
svg_tag
end
end
end
end
Liquid::Template.register_tag("icon", Jekyll::Tags::IconTag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment