import operator import re from django import template register = template.Library() a_re = re.compile(r'\s*(.*)\s*') space_re = re.compile(r'\s+') @register.tag def anchorsort(parser, token): """ Sorts a list of links, Anchor Text. """ nodelist = parser.parse(('endanchorsort',)) parser.delete_first_token() return AnchorSortNode(nodelist) class AnchorSortNode(template.Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): content = self.nodelist.render(context) try: anchorlist = [space_re.sub(" ", a).strip() for a in content.split("") if len(a.strip())] # Compose the list of tuples, (text, text) and sort it based on the first item. anchorlist = [(a_re.search(x).groups(1)[0].lower(), x) for x in anchorlist] anchorlist.sort(key=operator.itemgetter(0)) return "".join([item[1] for item in anchorlist]) + "" if anchorlist else "" except: return content