- Author:
- jcroft
- Posted:
- February 27, 2007
- Language:
- Python
- Version:
- Pre .96
- Score:
- 11 (after 15 ratings)
This is a simple filter I use to display a list of links from a blog entry off in the sidebar (example).
Requires beautifulsoup. Originally by Nathan Borror, tweaked slightly by me.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | def getlinks(value):
try:
import beautifulsoup
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError, "Error in {% getlinks %} filter: The Python BeautifulSoup and/or urllib2 libraries aren't installed."
return value
else:
soup = beautifulsoup.BeautifulSoup(value)
return soup.findAll('a')
"""
Returns links found in an (X)HTML string as Python objects for itteration in templates.
EXAMPLE:
<ul>
{% for link in blog.entry.body|getlinks %}
<li><a href="{{ link.href }}">{{ link.title }}</a></li>
{% endfor %}
</ul>
"""
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Aah, wonderful - I always wondered how you did this!
#
Thanks. I just wondered how to implement this.
#
Separately* ^-^
Also, someone posted a duplicate.
#
Please login first before commenting.