💾 Archived View for mozz.us › markdown › render_html.py captured on 2022-07-16 at 14:51:28.
⬅️ Previous capture (2020-09-24)
-=-=-=-=-=-=-
#!/usr/bin/env python3 """ Convert a JSON-encoded Gemini AST into an HTML document. """ from html import escape def render_html(ast): body = ['<div style="max-width: 38rem; padding: 2rem; margin: auto">'] for name, value in ast: if name == 'Horizontal Rule': body.append('<hr>') elif name == 'Title': body.append(f'<h1>{escape(value)}</h1>') elif name == 'Heading': body.append(f'<h2>{escape(value)}</h2>') elif name == 'Sub-Heading': body.append(f'<h3>{escape(value)}</h3>') elif name == 'Paragraph': body.append(f'<p>{escape(value)}</p>') elif name == 'Preformatted': body.append(f'<pre>{escape(value)}</pre>') elif name == 'Ordered List': body.append('<ol>') body.extend([f'<li>{escape(item)}</li>' for item in value]) body.append('</ol>') elif name == 'Unordered List': body.append('<ul>') body.extend([f'<li>{escape(item)}</li>' for item in value]) body.append('</ul>') elif name == 'Link': body.append('<div>') body.append(f'<a href="{escape(value[0])}">{escape(value[1])}</a>') body.append('</div>') else: raise ValueError(f'Unrecognized node name `{name}`') body.append('</div>') return '\n'.join(body) def main(): import argparse import sys import json parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('infile', type=argparse.FileType('r'), default=sys.stdin) args = parser.parse_args() ast = json.load(args.infile) html = render_html(ast) sys.stdout.write(html) if __name__ == '__main__': main()