Created
February 7, 2010 18:02
-
-
Save eyeseast/297563 to your computer and use it in GitHub Desktop.
Template filter to add paragraph-level permalinks to a block of HTML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from django import template | |
| from BeautifulSoup import BeautifulSoup, Tag, NavigableString | |
| register = template.Library() | |
| @register.filter | |
| def enumerate_paras(html): | |
| """ | |
| Given a block of HTML, create id attributes on each | |
| paragraph (p) and write in a link at the end of each. | |
| >>> html = '''<p>First line.</p> | |
| ... <p>Second line.</p>''' | |
| >>> print enumerate_paras(html) | |
| <p id="p0">First line.<a href="#p0" title="Link to this paragraph"> #</a></p> | |
| <p id="p1">Second line.<a href="#p1" title="Link to this paragraph"> #</a></p> | |
| """ | |
| soup = BeautifulSoup(html) | |
| paras = soup.findAll('p', recursive=False) | |
| for i, p in enumerate(paras): | |
| p['id'] = 'p%s' % i | |
| a = Tag(soup, 'a') | |
| a['href'] = '#p%s' % i | |
| a['title'] = 'Link to this paragraph' | |
| a.insert(0, NavigableString(' #')) # link text | |
| p.append(a) # just add our new a tag to the end of p's contents | |
| return soup.renderContents() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment