Login

tag to store a settings value as template variable

Author:
pflanno
Posted:
July 6, 2011
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Get any value from settings.py as a template variable. The variable can then be used in conditional tags. E.g. to show a link to a help page only if it the help page url is defined in settings.py

{% load get_setting %}
{% get_setting MY_HELP_URL as help_url %}
{% if help_url %}<a href="{% help_url|safe %}">Help</a>{% endif %}
 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
import re
from django.template import Library, Node, TemplateSyntaxError
from django.conf import settings

# E.g. to use the value of MY_HELP_URL from settings.py in a template
# {% get_setting MY_HELP_URL as help_url %} 
# {% if help_url %}<a href="{% help_url %}">Help</a>{% endif %}

class SettingNode(Node):
    def __init__(self, settingname, var_name):
        self.settingname = settingname
        self.var_name = var_name
    def render(self, context):
        context[self.var_name] = getattr(settings, self.settingname, '')
        return ''

@register.tag()
def get_setting(parser, token):
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise TemplateSyntaxError("%r tag requires arguments" % token.contents.split()[0])
    m = re.search(r'(.*?) as (\w+)', arg)
    if not m:
        raise TemplateSyntaxError("%r tag had invalid arguments" % tag_name)
    param, var_name = m.groups()
    # strip quotes if present
    if ( (param[0] in ('"', "'")) and param[0] == param[-1] ):
        param = param[1:-1]
    return SettingNode(param, var_name)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

Please login first before commenting.