Set a variable in Django template

Summary

1. Create “templatetags” folder at the same level as models.py, views.py.

2. Create “__init__.py” file in “templatetags” folder. The content will be empty.

3. Create “set_var.py” file in “templatetags” folder. And copy and paste below code

from django import template
 
register = template.Library()
 
class SetVarNode(template.Node):
 
    def __init__(self, var_name, var_value):
        self.var_name = var_name
        self.var_value = var_value
 
    def render(self, context):
        try:
            value = template.Variable(self.var_value).resolve(context)
        except template.VariableDoesNotExist:
            value = ""
        context[self.var_name] = value
        return u""
 
def set_var(parser, token):
    """
        {% set <var_name>  = <var_value> %}
    """
    parts = token.split_contents()
    if len(parts) < 4:
        raise template.TemplateSyntaxError("'set' tag must be of the form:  {% set <var_name>  = <var_value> %}")
    return SetVarNode(parts[1], parts[3])
 
register.tag('set', set_var)

 

4. In template html file, add “{% load set_var %}” after {% extends ‘base.html’ %}

5. You can use it as below

{% load set_var %}

{% set class = 'alert-info' %}

{% if message.type == 'error' %}
    {% set class = 'alert-danger' %}
{% elif message.type == 'success' %}
    {% set class = 'alert-success' %}
{% endif %}

Reference: http://www.soyoucode.com/2011/set-variable-django-template, https://docs.djangoproject.com/en/1.2/howto/custom-template-tags/#code-layout

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.