From 38594a382bb997164e8e4554d0635d988aec194c Mon Sep 17 00:00:00 2001 From: Noah Petherbridge Date: Fri, 17 Jun 2016 14:54:45 -0700 Subject: [PATCH] Add hooks for Markdown pages to render their own table of contents --- rophako/utils.py | 34 ++++++++++++++++++++++++++++++++++ rophako/www/markdown.inc.html | 14 +++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/rophako/utils.py b/rophako/utils.py index 55021c0..4c1240c 100644 --- a/rophako/utils.py +++ b/rophako/utils.py @@ -130,6 +130,7 @@ def markdown_template(path): content = list() # New set of lines, without meta info. extensions = set() blacklist = set() # Blacklisted extensions + toc = False # Render a table of contents for line in lines: if line.startswith(":meta"): parts = line.split(" ") @@ -143,6 +144,9 @@ def markdown_template(path): blacklist.add(extension) else: extensions.add(extension) + elif parts[1] == "toc": + # Table of contents. + toc = parts[2] == "on" else: content.append(line) @@ -155,9 +159,16 @@ def markdown_template(path): extensions=extensions, blacklist=blacklist, ) + + # Including a table of contents? + nav = None + if toc: + nav = parse_anchors(rendered) + return template("markdown.inc.html", title=first, markdown=rendered, + toc=nav, ) @@ -202,6 +213,29 @@ def render_markdown(body, html_escape=True, extensions=None, blacklist=None): ) +def parse_anchors(html): + """Parse HTML code and identify anchor tags for Table of Contents. + + Args: + * str html: HTML code generated by `render_markdown()` + + Returns: + * list of dicts containing the parsed table of contents, with keys + including `id`, `level` (

level as int) and `text` + """ + toc = [] + + regexp = re.compile(r'(.+?)') + for match in re.findall(regexp, html): + toc.append(dict( + id=match[1], + level=int(match[0]), + text=match[2], + )) + + return toc + + def send_email(to, subject, message, sender=None, reply_to=None): """Send an e-mail out.""" if sender is None: diff --git a/rophako/www/markdown.inc.html b/rophako/www/markdown.inc.html index b75b91e..911b646 100644 --- a/rophako/www/markdown.inc.html +++ b/rophako/www/markdown.inc.html @@ -2,6 +2,18 @@ {% block title %}{{ title }}{% endblock %} {% block content %} +{% if toc %} + +{% endif %} + {{ markdown|safe }} -{% endblock %} \ No newline at end of file +{% endblock %}