extract_toc.py 936 B

1234567891011121314151617181920212223242526272829303132333435
  1. # -*- coding: utf-8 -*-
  2. """
  3. Extract Table of Content
  4. ========================
  5. A Pelican plugin to extract table of contents (ToC) from `article.content` and
  6. place it in its own `article.toc` variable for use in templates.
  7. """
  8. from os import path
  9. from bs4 import BeautifulSoup
  10. from pelican import signals, readers, contents
  11. def extract_toc(content):
  12. if isinstance(content, contents.Static):
  13. return
  14. soup = BeautifulSoup(content._content,'html.parser')
  15. toc = None
  16. if not toc: # default Markdown reader
  17. toc = soup.find('div', class_='toc')
  18. if not toc: # default reStructuredText reader
  19. toc = soup.find('div', class_='contents topic')
  20. if not toc: # Pandoc reader
  21. toc = soup.find('nav', id='TOC')
  22. if toc:
  23. toc.extract()
  24. content._content = soup.decode()
  25. content.toc = toc.decode()
  26. def register():
  27. signals.content_object_init.connect(extract_toc)