Login

Template Tag for Retrieving complex Settings

Author:
joelbitar
Posted:
February 7, 2011
Language:
Python
Version:
1.2
Tags:
settings template tag
Score:
0 (after 0 ratings)

Very much like the snippet joshua wrote (http://djangosnippets.org/snippets/67/) for the same purpose but with the addition that this lets the user get values for more complex settings like dicts and lists

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from django import template
from django.conf import settings
register = template.Library()

"""
Usage:

{% setting DEBUG %}
or
{% setting DATABASES.default.NAME %} # Get the name of the database
or
{% setting INSTALLED_APPS.2 %}  #get the third installed app.
or
{% setting DEBUG %}
"""

@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:
            setting = settings
            # Enables param to tag to be for example "DATABASES.default.ENGINE"
            for name in self.option.split('.'):
                # if is an int. get from the setting by index.
                if name.isdigit():
                    setting = setting[int(name)]
                else:
                    if type(setting) == dict:
                        setting = setting.get(name)
                    else:
                        setting = setting.__getattr__(name)
            
            return str(setting)
        except:
            return ""

More like this

  1. View to retrieve objects meeting a complex tag query by nathangeffen 4 years, 8 months ago
  2. blocksetter by jerzyk 7 years, 8 months ago
  3. CommaSeparatedIntegerField with CheckboxSelectMultiple Widget by brendansellers 2 years, 8 months ago
  4. Custom Template Tag - No Translate by robcharlwood 5 years, 4 months ago
  5. Template tag to dump database query info by pryankster 8 years, 5 months ago

Comments

Please login first before commenting.