Login

Find all links in a value and display them separatley

Author:
jcroft
Posted:
February 27, 2007
Language:
Python
Version:
Pre .96
Tags:
template filter beautifulsoup
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. @reply links in Twitter messages by ryanberg 6 years, 8 months ago
  2. urlize HTML by maguspk 4 years, 8 months ago
  3. Revisiting Pygments and Markdown by djypsy 7 years, 6 months ago
  4. Template filter for internal links in TextFields by bobtiki 3 months, 3 weeks ago
  5. youtubize template tag by TheJester 7 years, 10 months 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.