Path: blob/main/_plugins/jekyll-icon-tag.rb
1677 views
# frozen_string_literal: true12module Jekyll3module Tags45# Our {% icon X %} tag6class IconTag < Liquid::Tag7def initialize(tag_name, text, tokens)8super9parts = text.strip.split10@text = parts[0]11@aria = true12return unless parts[1] == 'aria=false'1314@aria = false15end1617##18# This function renders the icon tag19# Params:20# +icon+:: The icon to render21# +@area+:: Whether to add aria-hidden22# +@text+:: The text to add to the icon23#24# Returns:25# The HTML for the icon26# Note: The icon text label is wrapped in a span with class27# "visually-hidden" to make it accessible to screen readers.28#29# Example:30# {% icon fa fa-github %}31# => <i class="fa fa-github" aria-hidden="true"></i>32# {% icon fa fa-github aria=false %}33# => <i class="fa fa-github"></i>34def render_for_text(icon)35if icon.empty?36raise SyntaxError, "No icon defined for: '#{@text}'. Please define it in `_config.yml` (under `icon-tag:`)."37end3839if icon.start_with?('fa')40if @aria41%(<i class="#{icon}" aria-hidden="true"></i><span class="visually-hidden">#{@text}</span>)42else43%(<i class="#{icon}" aria-hidden="true"></i>)44end45elsif icon.start_with?('ai')46if @aria47%(<i class="ai #{icon}" aria-hidden="true"></i><span class="visually-hidden">#{@text}</span>)48else49%(<i class="ai #{icon}" aria-hidden="true"></i>)50end51end52end5354##55# icon - Include an icon from our _config.yml into your tutorial56#57# Examples:58#59# {% icon email %}60# {% icon galaxy-history %}61#62def render(context)63cfg = get_config(context)64icon = cfg[@text] || ''65render_for_text(icon)66end6768def get_config(context)69context.registers[:site].config['icon-tag']70end71end7273# The variable version that can accept a variable name instead of a string74class IconTagVar < IconTag75def initialize(tag_name, text, tokens)76super77@text = text.strip78end7980##81# icon_var - Include an icon from our _config.yml into your tutorial, but accessing a variable rather than expecting a string.82#83# Examples:84#85# {% icon_var var1 %}86# {% icon_var var2 %}87#88def render(context)89cfg = get_config(context)90icon = cfg[context[@text]] || ''91render_for_text(icon)92end93end94end95end9697Liquid::Template.register_tag('icon_var', Jekyll::Tags::IconTagVar)98Liquid::Template.register_tag('icon', Jekyll::Tags::IconTag)99100101