Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Batch conversion of Markdown to HTML.
#!/usr/bin/env ruby
require "fileutils"
require "redcarpet"
OUTPUT_FOLDER = "html"
HTML_TEMPLATE = <<-HTML
<!DOCTYPE html>
<html>
<head>
<meta encoding="utf-8" />
<title>%s</title>
<style>
body { margin-top: 3em; }
.content { width: 33em; margin-left: 7em; margin-right: auto; }
</style>
</head>
<body>
%s
</body>
</html>
HTML
# Delete and recreate output folder.
FileUtils.rm_rf(OUTPUT_FOLDER)
Dir.mkdir(OUTPUT_FOLDER)
# Create Markdown to HTML converter.
converter = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
# Get all Markdown files in current folder and all subfolders.
Dir["**/*.markdown", "**/*.mdown", "**/*.md"].each do |file|
begin
# Construct output filename including original path.
input_file = File.path(file)
basename = File.basename(file, File.extname(file))
output_file = File.basename(File.path(file).gsub("/", "-"), File.extname(file)) + ".html"
# Convert Markdown to HTML.
puts "#{input_file} >> #{output_file}"
markdown = IO.read(file)
html = converter.render(markdown)
output = HTML_TEMPLATE % [basename, html]
# Write HTML to new file.
IO.write(File.join(OUTPUT_FOLDER, output_file), output)
rescue
puts $!.inspect, $@
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.