Login

Hyperlink list filter

Author:
lifefloatsby
Posted:
January 3, 2008
Language:
Python
Version:
.96
Tags:
filter templatetag links template-tag link hyperlink
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 ',&nbsp;'.join(links)
	# else return an empty string
	else:
		return ''

register.filter('hyperlink_list', hyperlink_list)

More like this

  1. Make hyperlinks for labels of raw_id_fields (jQuery) by ramen 5 years, 7 months ago
  2. keeping filter states after edits by chronosllc 3 years, 11 months ago
  3. Additional Change List Columns by sansmojo 8 years ago
  4. Template filter for internal links in TextFields by bobtiki 8 months, 3 weeks ago
  5. Keeping filter states after edits (Django 1.4) by rhfung 2 years, 8 months ago

Comments

Please login first before commenting.