Login

"Link To" helper tag

Author:
jdriscoll
Posted:
October 9, 2007
Language:
Python
Version:
.96
Tags:
template models links tags anchors
Score:
0 (after 0 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. "If in" template tag by andrew 6 years, 10 months ago
  2. Delicious Tag by alcides 6 years, 8 months ago
  3. "Youtube watch link to embed" custom tag. by I159 3 years, 5 months ago
  4. E-mail quoting filters and tags by ChipX86 7 years, 8 months ago
  5. Random Quotes by ferretsrule 7 years, 8 months ago

Comments

Please login first before commenting.