Created
November 10, 2021 17:45
-
-
Save timblair/544d9ae88720377a6e9771f3b81307c3 to your computer and use it in GitHub Desktop.
Generating headers with IDs using CommonMarker
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
require "commonmarker" | |
class HeaderWithIdRender < CommonMarker::HtmlRenderer | |
def header(node) | |
block do | |
old_stream = @stream | |
@stream = StringIO.new(String.new.force_encoding("utf-8")) | |
out(:children) | |
content = @stream.string | |
@stream = old_stream | |
id = generate_id(content) | |
out("<h", node.header_level, " id=\"", id, "\">", | |
content, "</h", node.header_level, ">") | |
end | |
end | |
def generate_id(content) | |
content.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') | |
end | |
end | |
markdown = "## My nice long header" | |
doc = CommonMarker.render_doc(markdown, :DEFAULT) | |
puts HeaderWithIdRender.new.render(doc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment