Skip to content

Instantly share code, notes, and snippets.

@joncombe
Created March 27, 2019 11:28
Show Gist options
  • Save joncombe/4d4153413525f09d738dd7d16d04e78e to your computer and use it in GitHub Desktop.
Save joncombe/4d4153413525f09d738dd7d16d04e78e to your computer and use it in GitHub Desktop.
Django template tag to access settings
"""
Please don't use this for PHP-esque in template treachery. It fixed an emergency I had. Maybe it can for you too.
Output a string...
{% setting "FOO.BAR" %}
Use in an expression...
{% setting "FOO.BAR" as foobar %}
{% if foobar %}yeah!{% else %}boo!{% endif %}
"""
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag()
def setting(path):
def get_value(source, item):
if isinstance(source, dict):
return source.get(item, '')
elif (isinstance(source, list) or isinstance(source, tuple)):
try:
return source[int(item)]
except:
pass
else:
try:
return getattr(source, item, '')
except:
pass
return ''
source = settings
path = path.split('.')
for item in path:
source = get_value(source, item)
if source == '':
break
return source
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment