Created
March 27, 2019 11:28
-
-
Save joncombe/4d4153413525f09d738dd7d16d04e78e to your computer and use it in GitHub Desktop.
Django template tag to access settings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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