Say I have a template
Hello {{name}}!
While testing it, it would be useful to define the
The app should contain a templatetags
directory, at the same level as models.py
, views.py
, etc. If this doesn’t already exist, create it - don’t forget the __init__.py
file to ensure the directory is treated as a Python package.
define_action.py
inside of the templatetags directory with the following code:from django import template
register = template.Library()
@register.simple_tag
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.
{% load define_action %}
{% if item %}
{% define "Edit" as action %}
{% else %}
{% define "Create" as action %}
{% endif %}
Would you like to {{action}} this item?
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.
Perhaps the default template filter wasn't an option back in 2009...
<html>
<div>Hello {{name|default:"World"}}!</div>
</html>