asciidoctor / kramdown-asciidoc

A kramdown extension for converting Markdown documents to AsciiDoc.
Other
207 stars 19 forks source link

Preserving frontmatter for hugo #82

Closed joelouthan closed 3 years ago

joelouthan commented 3 years ago

Hello,

Thank you for creating kramdown.

I am converting md files in Hugo.

How can I use kramdown to convert and still preserve the frontmatter? Hugo will not render with frontmatter.

mojavelinux commented 3 years ago

I would recommend skimming of the front matter first, running the remainder through kramdoc, then adding the front matter back on top. Front matter is not part of either AsciiDoc or Markdown, so you cannot expect a processor to deal with it.

Thank you for creating kramdown.

I did not create Kramdown. I did create kramdown-asciidoc (aka kramdoc), though.

mojavelinux commented 3 years ago

This converter provides a preprocessor hook that you can use for this. Here's an example of how to use it:

require 'kramdown-asciidoc'
require 'toml'

extract_hugo_front_matter = -> (source, attributes) {
  if (line_i = (lines = source.each_line).first) && line_i.chomp == '+++'
    lines = lines.drop 1
    front_matter = []
    while (line = lines.shift) && line.chomp != '+++'
      front_matter << line
    end
    return source unless line && line.chomp == '+++' && !(front_matter.include? ?\n)
    lines.shift while (line = lines[0]) && line == ?\n
    (::TOML.load front_matter.join).each do |key, val|
      attributes[key] = val.to_s
    end unless front_matter.empty?
    lines.join
  else
    source
  end
}

Kramdown::AsciiDoc.convert_file with-hugo-front-matter.md',
  preprocessors: [extract_hugo_front_matter] + Kramdown::AsciiDoc::DEFAULT_PREPROCESSORS