How to set a value of a variable inside a template code?


Say I have a template

<div>Hello {{name}}!</div>

While testing it, it would be useful to define the value of the variable without touching the python code that invokes this template. So I'm looking for something like this

{% set name="World" %}     
<div>Hello {{name}}!</div>

Does something like this exists in Django?

5/28/2016 12:11:40 PM

Accepted Answer

You can use the with template tag.

{% with name="World" %}     
<div>Hello {{name}}!</div>
{% endwith %}
6/10/2019 9:14:32 PM

Create a template tag:

The app should contain a templatetags directory, at the same level as,, etc. If this doesn’t already exist, create it - don’t forget the file to ensure the directory is treated as a Python package.

Create a file named inside of the templatetags directory with the following code:

from django import template
register = template.Library()

def define(val=None):
  return val

Note: Development server won’t automatically restart. After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.

Then in your template you can assign values to the context like this:

{% load define_action %}
{% if item %}

   {% define "Edit" as action %}

{% else %}

   {% define "Create" as action %}

{% endif %}

Would you like to {{action}} this item?

An alternative way that doesn't require that you put everything in the "with" block is to create a custom tag that adds a new variable to the context. As in:

class SetVarNode(template.Node):
    def __init__(self, new_val, var_name):
        self.new_val = new_val
        self.var_name = var_name
    def render(self, context):
        context[self.var_name] = self.new_val
        return ''

import re
def setvar(parser,token):
    # This version uses a regular expression to parse tag contents.
        # Splitting by None == splitting by spaces.
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
    m ='(.*?) as (\w+)', arg)
    if not m:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name
    new_val, var_name = m.groups()
    if not (new_val[0] == new_val[-1] and new_val[0] in ('"', "'")):
        raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
    return SetVarNode(new_val[1:-1], var_name)

This will allow you to write something like this in your template:

{% setvar "a string" as new_template_var %}

Note that most of this was taken from here


There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
Because of this, the recommended way to change any variable is via touching the Python code.


The best solution for this is to write a custom assignment_tag. This solution is more clean than using a with tag because it achieves a very clear separation between logic and styling.

Start by creating a template tag file (eg. appname/templatetags/

from django import template

register = template.Library()

def get_addressee():
    return "World"

Now you may use the get_addressee template tag in your templates:

{% load hello_world %}

{% get_addressee as addressee %}

        <h1>hello {{addressee}}</h1>

Perhaps the default template filter wasn't an option back in 2009...

<div>Hello {{name|default:"World"}}!</div>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]