- Author:
- lifefloatsby
- Posted:
- January 3, 2008
- Language:
- Python
- Version:
- .96
- Score:
- 0 (after 0 ratings)
This is a simple filter that takes an object list and returns a comma-separated list of hyperlinks. I use it to display the list of tags in my blog entries.
The function assumes the object has a get_absolute_url()
method that returns the URL. In your template, write {{ obj_list|hyperlink_list:"slug" }}
where obj_list
is your object list and "slug"
is the object's attribute that returns the link text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | from django.template import Library
register = Library()
def hyperlink_list(obj_list, arg):
"""Converts an object list into a comma-separated list of hyperlinks.
Assumes obj.get_absolute_url() returns the link URL.
arg is the name of the object's attribute (as a string) that returns
the link text.
Template usage: {{ obj_list|hyperlink_list:"slug" }}"""
links = [] # start with an empty list of links
for obj in obj_list:
# initialize url and text to None
url = None
text = None
try:
url = obj.get_absolute_url() # get the URL
except:
pass # if any exceptions occur, do nothing to leave url == None
try:
text = getattr(obj, arg) # get the link text
except:
pass # if any exceptions occur, do nothing to leave text == None
# if both URL and text are present, return the HTML for the hyperlink
if url and text:
links.append('<a href="%s">%s</a>' % (url, text))
# if no URL but text is present, return unlinked text
elif not url and text:
links.append(text)
# if the list has anything in it, return the list items joined
# by a comma and a non-breaking space (in HTML)
if len(links) > 0:
return ', '.join(links)
# else return an empty string
else:
return ''
register.filter('hyperlink_list', hyperlink_list)
|
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
Please login first before commenting.