Skip to content

Instantly share code, notes, and snippets.

@timblair
Created November 10, 2021 17:45
Show Gist options
  • Save timblair/544d9ae88720377a6e9771f3b81307c3 to your computer and use it in GitHub Desktop.
Save timblair/544d9ae88720377a6e9771f3b81307c3 to your computer and use it in GitHub Desktop.
Generating headers with IDs using CommonMarker
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