Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Conditional Django template tag to check if one or more apps exist. Usage: {% ifappexists tag %} ... {% endifappexists %}, or {% ifappexists tag inventory %} ... {% else %} ... {% endifappexists %}

View ifappexists_tag.py
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 48 49 50 51 52 53 54 55 56 57 58
from django.template import Library
from django import template
from app import settings
 
register = Library()
 
@register.tag
def ifappexists(parser, token):
""" Conditional Django template tag to check if one or more apps exist.
Usage: {% ifappexists tag %} ... {% endifappexists %}, or
{% ifappexists tag inventory %} ... {% else %} ... {% endifappexists %}
"""
try:
tokens = token.split_contents()
apps = []
apps += tokens[1:]
except ValueError:
raise template.TemplateSyntaxError("Tag 'ifappexists' requires at least 1 argument.")
 
nodelist_true = parser.parse(('else', 'endifappexists'))
token = parser.next_token()
 
if token.contents == 'else':
nodelist_false = parser.parse(('endifappexists',))
parser.delete_first_token()
else:
nodelist_false = template.NodeList()
 
return AppCheckNode(apps, nodelist_true, nodelist_false)
 
 
class AppCheckNode(template.Node):
def __init__(self, apps, nodelist_true, nodelist_false):
self.apps = apps
self.nodelist_true = nodelist_true
self.nodelist_false = nodelist_false
 
def render(self, context):
allowed = False
for app in self.apps:
 
if app.startswith('"') and app.endswith('"'):
app = app[1:-1]
 
if app.startswith("'") and app.endswith("'"):
app = app[1:-1]
 
if app in settings.INSTALLED_APPS:
allowed = True
else:
break
 
if allowed:
return self.nodelist_true.render(context)
else:
return self.nodelist_false.render(context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.