Login

Find all links in a value and display them separatley

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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 3 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

obeattie (on February 28, 2007):

Aah, wonderful - I always wondered how you did this!

#

kaikuehne (on February 28, 2007):

Thanks. I just wondered how to implement this.

#

joshua (on March 3, 2007):

Separately* ^-^

Also, someone posted a duplicate.

#

Please login first before commenting.