Template Tag for Retrieving Settings

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django import template
from django.conf import settings
register = template.Library()

@register.tag
def setting ( parser, token ): 
    try:
        tag_name, option = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents[0]
    return SettingNode( option )

class SettingNode ( template.Node ): 
    def __init__ ( self, option ): 
        self.option = option

    def render ( self, context ): 
        # if FAILURE then FAIL silently
        try:
            return str(settings.__getattr__(self.option))
        except:
            return ""

More like this

  1. Template tag to dump database query info by pryankster 7 years ago
  2. tag to store a settings value as template variable by pflanno 2 years, 9 months ago
  3. Easy Conditional Template Tags by fragsworth 4 years, 10 months ago
  4. Paginator Tag for 1.x by HM 5 years ago
  5. simple tag-cloud Template Tag by metty 4 years, 6 months ago

Comments

wiz (on March 1, 2007):

"be generic" (c)

@register.simpletag
def setting(name):
    return str(settings.__getattr__(name))

#

whiskybar (on March 2, 2007):

In fact, I want settings so often that I put that into context:

settings.py

....
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.debug', #and other common context_processors
    'yourapp.context_processors.settings', 
)

context_processors.py

from django.conf import settings as _settings

def settings(request):
    return {'settings': _settings}

#

grimboy (on March 6, 2007):

from django.conf import settings register = template.Library()

@register.simpletag
def setting(name):
    import pprint
    pp = pprint.PrettyPrinter(indent=4)
    return "<pre>%s</pre>" % (pp.pformat(settings.__getattr__(name)),)

#

graham (on August 20, 2009):

The decorator is missing an underscore:

@register.simple_tag

#

graham (on August 20, 2009):

In your template, the key name must be quoted:

{% setting 'DEBUG' %}

#

(Forgotten your password?)