I didn't think of the potential security implications of this until I wrote it up (think {% get_setting DATABASE_PASSWORD %}), but I think it could prove quite useful as a default templatetag.
class SettingNode(Node):
def __init__(self, varname, setting):
self.setting = setting
self.varname = varname
def render(self, context):
context[self.varname] = self.setting
return ""
#@register.tag
def get_setting(parser, token):
"""
Retrieve a setting from the current settings file. The optional as clause can control
the variable to be added to the context, otherwise the setting asked for witll be added to
the context. For example::
{% get_setting MEDIA_URL [as varname] %}
If the setting does not exist in the current settings file, ``None`` will be returned. The
following example will return a bulleted list of installed apps::
{% get_setting INSTALLED_APPS %}
<ul>
{% for app in INSTALLED_APPS %}
<li>{{ app }}</li>
{% endfor %}
</ul>
"""
bits = token.contents.split()
if len(bits) == 2:
varname = bits[1]
elif len(bits == 4):
varname = bits[3]
else:
raise TemplateSyntaxError, "'%s' takes either one or three arguments." % bits[0]
try:
setting = bits[1]
imp = __import__('django.conf.settings', locals(), globals(), bits[1])
retsetting = getattr(imp, bits[1])
except AttributeError:
retsetting = None
return SettingNode(varname, retsetting)
get_setting = register.tag('get_setting', get_setting)