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)
|
Comments