wordpusher/render_file

57 lines
2.0 KiB
Bash
Executable File

#!/bin/sh
# render_file.sh: render a markdown file as HTML
# arguments:
# $1: markdown file to render
# Determine location of this script
script_dir=$(dirname "$0")
# Separate metadata and actual markdown in the .md file
frontmatter=$(awk '/!startmeta/,/!endmeta/ {if ($0 != "!startmeta" && $0 != "!endmeta") print;}' "$1")
docbody=$(awk '/!endmeta/ {p=1; next} p' "$1")
title=$(echo "$frontmatter" | awk -F'=' '/title=/ {print $2}')
date=$(echo "$frontmatter" | awk -F'=' '/date=/ {print $2}')
# Attempt to dynamically generate the header and footer for this page from gentemplates
# (If no script for generation exists, skip the step for that page element)
if [ -f gentemplate/header ]
then
printf 'Generating page header...' >&2
title="$title" date="$date" "$script_dir"/gentemplate/header
fi
if [ -f gentemplate/footer ]
then
printf 'Generating page footer...' >&2
date="$date" "$script_dir"/gentemplate/footer
fi
if [ -f gentemplate/htmlhead ]
then
printf 'Generating page <head>...' >&2
title="$title" "$script_dir"/gentemplate/htmlhead
fi
# cmark doesn't create the <head>, doctype declaration or indeed most of the document
# structure for us, so we'll do it ourselves.
# We're going to use single quotes for the strings here too because otherwise we'll have
# to escape all the double quotes in the HTML
printf '<!doctype html>\n'
printf '<html>\n'
printf '<head>\n'
# At this point, insert the <head>
printf "%s\n" "$(cat "$script_dir"/template/htmlhead)"
printf '</head>\n'
printf '<body>\n'
printf '<header>\n'
# Now insert the header
printf "%s\n" "$(cat "$script_dir"/template/header)"
printf '</header>\n'
printf '<main>\n'
# Now we insert the main content of the page
# Also insert a <date> element in the header after the heading, based on the `date` metadata item
printf '%s' "$(echo "$docbody" | cmark)"
printf '</main>\n'
# Finally, the footer
printf '<footer>\n'
printf '%s\n' "$(cat "$script_dir"/template/footer)"
printf '</footer>\n'
printf '</body>\n'
printf '</html>\n'