Login

Create new variables in templates

Author:
jmrbcu
Posted:
January 9, 2008
Language:
Python
Version:
.96
Score:
8 (after 8 ratings)

Sometimes you want to create a temporal variable to store something or do anything you want with it, problem is that django template system doesn't provide this kind of feature. This template tag is just for that.

Syntax::

    {% assign [name] [value] %}

This will create a context variable named [name] with a value of [value] [name] can be any identifier and [value] can be anything. If [value] is a callable, it will be called first and the returning result will be assigned to [name]. [value] can even be filtered.

Example::

{% assign count 0 %} {% assign str "an string" %} {% assign number 10 %} {% assign list entry.get_related %} {% assign other_str "another"|capfirst %}

{% ifequal count 0 %} ... {% endifequal %}

{% ifequal str "an string" %} ... {% endifequal %}

{% if list %} {% for item in list %} ... {% endfor %} {% 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
from django import template

class AssignNode(template.Node):
    def __init__(self, name, value):
        self.name = name
        self.value = value
        
    def render(self, context):
        context[self.name] = self.value.resolve(context, True)
        return ''

def do_assign(parser, token):
    """
    Assign an expression to a variable in the current context.
    
    Syntax::
        {% assign [name] [value] %}
    Example::
        {% assign list entry.get_related %}
        
    """
    bits = token.contents.split()
    if len(bits) != 3:
        raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
    value = parser.compile_filter(bits[2])
    return AssignNode(bits[1], value)

register = template.Library()
register.tag('assign', do_assign)

More like this

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

Comments

fivethreeo (on February 6, 2008):

A bug, forgot a template.Variable in there ?

#

chodorowicz (on January 29, 2011):

This is really useful, but it breaks if you use string with spaces as as the value - {% assign str "an string" %} produces: 'assign' tag takes two arguments

Exchanging token.contents.split() to token.split_contents() solves the problem

#

piasekps (on January 10, 2016):

I got a question if I assign a variable inside for loop block, I have no access to it outside for loop block. Do you know how I can access this value?

#

logston (on March 15, 2016):

+1 Thanks!

#

Please login first before commenting.