Login

Template Tag for Retrieving Settings

Author:
joshua
Posted:
March 1, 2007
Language:
Python
Version:
Pre .96
Tags:
template tag settings
Score:
6 (after 6 ratings)

Useage: {% load setting %} {% setting DEBUG %} or... {% setting MEDIA_ROOT %}

You get the gist.

 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

Comments

wiz (on March 1, 2007):
<p>"be generic" (c)</p> <pre>@register.simpletag def setting(name): return str(settings.__getattr__(name)) </pre>

#

whiskybar (on March 2, 2007):
<p>In fact, I want settings so often that I put that into context:</p> <p>settings.py</p> <pre>.... TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.debug', #and other common context_processors 'yourapp.context_processors.settings', ) </pre> <p>context_processors.py</p> <pre>from django.conf import settings as _settings def settings(request): return {'settings': _settings} </pre>

#

grimboy (on March 6, 2007):
<p>from django.conf import settings register = template.Library()</p> <pre>@register.simpletag def setting(name): import pprint pp = pprint.PrettyPrinter(indent=4) return "<pre>%s</pre>" % (pp.pformat(settings.__getattr__(name)),) </pre>

#

graham (on August 20, 2009):
<p>The decorator is missing an underscore:</p> <p>@register.simple_tag</p>

#

graham (on August 20, 2009):
<p>In your template, the key name must be quoted:</p> <p>{% setting 'DEBUG' %}</p>

#

Please login first before commenting.