Autogenerated ToC

November 24, 2007 [last comment: November 25, 2007]

When I reread my last blog post WebAlchemy accelerates Django in 100 times I realized that I wrote too many letters. So to make navigation easy I created simple template filter that extracts from a text ids, replaces '_' with spaces and produces hyperlinked Table of Contents.

@register.filter
def toc(text):
    """Extract IDs from text and return Table of Contents,
    as list of tuples (id, name)."""
    items = []
    for i in re.finditer(r'<[^>]*?id="(?P<id>[^"]*?)".*?>', text):
        _id = i.group('id')
        items.append({'id':_id, 'name': _id.replace('_', ' ').strip()})
    return items

The usage of this template filter is even more simple that tag itself.

<h3>Table of Contents<h3>
<ul>
{% for item in object.content|toc %}
<li><a href="#{{ item.id }}">{{ item.name }}</a></li>
{% endfor %}
</ul>

This entry is not very good candidate for template tag demonstration but already mentioned WebAlchemy accelerates Django in 100 times have autogenerated Table of Contents.

Tags: concept  django  tips 
Submitted 2 comments: accepted - 2, in moderation queue - 0. Add your comment.
  • Max Battcher on November 24, 2007
    Interesting. What sort of markup system are you using? Some markup systems will give you the table of contents nearly automatically. ReStructuredText is very useful for that (and what Django's website uses for the documentation pages' table of contents links).
  • Dima Dogadaylo on November 25, 2007
    Max, I use old good html. ReST and etc are very good for docs that can be converted in different formats but for me for blog posts I don't see advantages of introducing additional layer between writer and reader.


   
Web log, research lab and soft parade of Dima Dogadaylo.
Email: entropyhacker at gmail dot com

Table of Contents