Login

Template tag to sort a list of links

Author:
pytechd
Posted:
August 17, 2007
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

Sorts a list of HTML anchor tags based on the anchor's contents. This is useful, for example, when combining a static list of links with a dynamic list that needs to be sorted alphabetically. It ignores all attributes of the HTML anchor.

{% load anchorsort %}

{% anchorsort %}
    <a href="afoo.jpg">Trip to Fiji</a>
    <a href="bfoo.jpg">Doe, a deer, a female deer!</a>
    {% for link in links %}
        <a class="extra" href="{{ link.href|escape }}">{{ link.name|escape }}</a>
    {% endfor %}
{% endanchorsort %}

Note that case (capital vs. lower) is ignored. Any HTMl within the node itself will not be removed, so sorting <a>Bar</a><a><strong>Foo</strong><a/> will sort as <a><strong>Foo</strong></a><a>Bar</a> because < is logically less than b.

 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
import operator
import re

from django import template


register = template.Library()
a_re = re.compile(r'<a.+?>\s*(.*)\s*')
space_re = re.compile(r'\s+')


@register.tag
def anchorsort(parser, token):
    """ Sorts a list of links, <a href="..."...>Anchor Text</a>. """
    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("</a>") if len(a.strip())]

            # Compose the list of tuples, (text, <a href...>text</a>) 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 "</a>".join([item[1] for item in anchorlist]) + "</a>" if anchorlist else ""
        except:
            return content

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.