Login

Link If templatetag

Author:
bmihelac
Posted:
January 3, 2013
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

Django templatetag wraps everything between {% linkif %} and {% endlinkif %} inside a link if link is not False.

Sample usage::

    {% linkif "http://example.com" %}link{% endlinkif %}
    {% linkif object.url %}link only if object has an url{% endlinkif %}
 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
from django import template
 
register = template.Library()
 
 
@register.tag
def linkif(parser, token):
    """
    Wraps everything between ``{% linkif %}`` and ``{% endlinkif %}`` inside
    a ``link`` if ``link`` is not False.
 
    Sample usage::
 
        {% linkif "http://example.com" %}link{% endlinkif %}
        {% linkif object.url %}link only if object has an url{% endlinkif %}
 
    """
    bits = token.split_contents()
    if len(bits) != 2:
        raise template.TemplateSyntaxError("'%s' takes one argument"
                                  " (link)" % bits[0])
    link = parser.compile_filter(bits[1])
    nodelist = parser.parse(('endlinkif',))
    parser.delete_first_token()
    return LinkIfNode(nodelist, link)
 
 
class LinkIfNode(template.Node):
 
    def __init__(self, nodelist, link):
        self.link = link
        self.nodelist = nodelist
 
    def render(self, context):
        output = self.nodelist.render(context)
        link = self.link.resolve(context)
        if link:
            output = '<a href="%s">%s</a>' % (link, output)
        return output

More like this

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

Comments

Please login first before commenting.