Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Hook to do heading permalinks automatically.

  • Loading branch information...
commit 28d45b64ce7eac8da4bb03776cb1a6e790f17376 1 parent 6c26ae1
@mythmon authored
View
0  wok/contrib/__init__.py
No changes.
View
51 wok/contrib/hooks.py
@@ -0,0 +1,51 @@
+# vim: set fileencoding=utf8 :
+"""Some hooks that might be useful."""
+
+from StringIO import StringIO
+import logging
+
+from wok.exceptions import DependencyException
+from wok.util import slugify
+
+try:
+ from lxml import etree
+except ImportError:
+ etree = None
+
+
+class HeadingAnchors(object):
+ """
+ Put some paragraph heading anchors.
+
+ Serves as a 'page.template.post' wok hook.
+ """
+
+ def __init__(self, max_heading=3):
+ if not etree:
+ raise DependencyException('To use the HeadingAnchors hook, you must '
+ 'install the library lxml.')
+ self.max_heading = max_heading
+ logging.debug('Loaded hook HeadingAnchors')
+
+ def __call__(self, page):
+ logging.debug('Called hook HeadingAnchors on {0}'.format(page))
+ parser = etree.HTMLParser()
+ sio_source = StringIO(page.rendered)
+ tree = etree.parse(sio_source, parser)
+
+ for lvl in range(1, self.max_heading+1):
+ headings = tree.iterfind('//h{0}'.format(lvl))
+ for heading in headings:
+ if not heading.text:
+ continue
+ logging.debug('[HeadingAnchors] {0} {1}'.format(heading, heading.text))
+ anchor = etree.Element('a')
+ anchor.set('class', 'heading_anchor')
+ anchor.set('href', '#heading-{0}'.format(slugify(heading.text)))
+ anchor.set('name', 'heading-{0}'.format(slugify(heading.text)))
+ anchor.text = u''
+ heading.append(anchor)
+
+ sio_destination = StringIO()
+ tree.write(sio_destination)
+ page.rendered = sio_destination.getvalue()
View
2  wok/exceptions.py
@@ -0,0 +1,2 @@
+class DependencyException(Exception):
+ pass
Please sign in to comment.
Something went wrong with that request. Please try again.