tag to store a settings value as template variable

 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. IfValueTag by adurdin 7 years, 1 month ago
  2. template tag for highlighting currently active page by adunar 5 years, 6 months ago
  3. Paginator TemplateTag by trbs 6 years ago
  4. Querystring Builder - create urls with GET params by jibberia 3 years, 3 months ago
  5. better paginator template tag by amitu 5 years, 6 months ago

Comments

(Forgotten your password?)