Last active
December 22, 2020 09:02
-
-
Save brandonmwest/6262934 to your computer and use it in GitHub Desktop.
Custom liquid block for Jekyll example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Generates a named anchor and wrapping tag from a string. | |
module Jekyll | |
class AnchorBlock < Liquid::Block | |
def initialize(tag_name, markup, tokens) | |
@tag = markup | |
super | |
end | |
def render(context) | |
contents = super | |
# pipe param through liquid to make additional replacements possible | |
content = Liquid::Template.parse(contents).render context | |
#strip out special chars and replace spaces with hyphens | |
safeContent = content.rstrip.gsub(/[^\w\s]/,'').gsub(/[\s]/,'-') | |
output = "<#{@tag} class=\"anchor-wrap\"><a name=\"#{safeContent}\" class=\"anchor\" href=\"##{safeContent}\">" | |
output += '<span class="anchor-icon"><i class="icon-link"></i></span></a>' | |
output += content.strip | |
output += "</#{@tag}>" | |
output | |
end | |
end | |
end | |
Liquid::Template.register_tag("anchor", Jekyll::AnchorBlock) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment