from django.core.urlresolvers import reverse, NoReverseMatch from django.template import Library, Variable, TemplateSyntaxError, Node register = Library() class RelatedNode(Node): def __init__(self, object_list, viewname): self.object_list = Variable(object_list) self.viewname = viewname def render(self, context): def node(object): try: reversed = reverse(self.viewname, args=[object.id]) except NoReverseMatch: return '
  • %s
  • ' % object return '
  • %s
  • ' % (reversed, object) def recursive(object): if object.child_set.all(): output.append('') output = [] for object in self.object_list.resolve(context): if not object.parent: output.append(node(object)) recursive(object) return '\n'.join(output) def related_linked_list(parser, token): bits = token.contents.split() if len(bits) != 3: raise TemplateSyntaxError, "'%s' tag takes exactly 2 arguments" % bits[0] return RelatedNode(bits[1], bits[2]) register.tag(related_linked_list)