Login

"Link To" helper tag

Author:
jdriscoll
Posted:
October 9, 2007
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

Simple template tag that assumes some common conventions in order to quickly get a link to a specific model instance.

 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
42
43
44
45
46
47
from django import template
from django.core.urlresolvers import reverse
from django.template import resolve_variable

register = template.Library()

@register.tag()
def link_to(parser, token):
    """ Generates a link to a model instance

    Attempts to determine a link to the supplied model instance by first looking
    for a "get_absolute_url" method. It then looks for a named url with the
    pattern "appname-modelname". Finally it returns a relative url to
    "/appname/modelname/instancepk/".

    Usage: {% link_to instance "Anchor text" %}

    """
    try:
        tag_name, instance, anchor_text = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("\"link_to\" tag requires two arguments.")
    return LinkToNode(instance, anchor_text)

class LinkToNode(template.Node):
    def __init__(self, instance, anchor_text):
        self.instance_name = instance
        self.anchor_text = anchor_text.strip("\"\'")
    def render(self, context):
        try:
            anchor_text = resolve_variable(self.anchor_text, context)
        except template.VariableDoesNotExist:
            anchor_text = self.anchor_text
        tpl = '<a href="%s">%s</a>'
        instance = resolve_variable(self.instance_name, context)
        if getattr(instance, "get_absolute_url", None):
            return tpl % (instance.get_absolute_url(), anchor_text)
        try:
            url = reverse("%s-%s" % (instance._meta.app_label,
                                     instance._meta.verbose_name),
                          args=[instance._get_pk_val()])
            return tpl % (url, anchor_text)
        except NoReverseMatch:
            url = "/%s/%s/%s/" % (instance._meta.app_label,
                                  instance._meta.verbose_name,
                                  instance._get_pk_val())
            return tpl % (url, anchor_text)

More like this

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

Comments

Please login first before commenting.