Skip to content

Instantly share code, notes, and snippets.

@bmihelac
Created January 2, 2013 14:48
Show Gist options
  • Save bmihelac/4435025 to your computer and use it in GitHub Desktop.
Save bmihelac/4435025 to your computer and use it in GitHub Desktop.
Django templatetag wraps everything between ``{% linkif %}`` and ``{% endlinkif %}`` inside a ``link`` if ``link`` is not False.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment