458đź‘Ť
You can use the with
template tag.
{% with name="World" %}
<html>
<div>Hello {{name}}!</div>
</html>
{% endwith %}
88đź‘Ť
Create a template tag:
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.
Create a file named 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.
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?
- [Django]-Django ignores router when running tests?
- [Django]-Get Timezone from City in Python/Django
- [Django]-How to change User representation in Django Admin when used as Foreign Key?
38đź‘Ť
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
@register.tag
def setvar(parser,token):
# This version uses a regular expression to parse tag contents.
try:
# 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 = re.search(r'(.*?) 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
- [Django]-How to run own daemon processes with Django?
- [Django]-Annotate a queryset with the average date difference? (django)
- [Django]-How to merge consecutive database migrations in django 1.9+?
36đź‘Ť
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.
- [Django]-How to use Django ImageField, and why use it at all?
- [Django]-On Heroku, is there danger in a Django syncdb / South migrate after the instance has already restarted with changed model code?
- [Django]-Adding to the "constructor" of a django model
16đź‘Ť
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/hello_world.py
):
from django import template
register = template.Library()
@register.simple_tag
def get_addressee():
return "World"
Now you may use the get_addressee
template tag in your templates:
{% load hello_world %}
{% get_addressee as addressee %}
<html>
<body>
<h1>hello {{addressee}}</h1>
</body>
</html>
- [Django]-How to customize activate_url on django-allauth?
- [Django]-Changing a project name in django
- [Django]-Django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"
14đź‘Ť
Perhaps the default
template filter wasn’t an option back in 2009…
<html>
<div>Hello {{name|default:"World"}}!</div>
</html>
- [Django]-Create a field whose value is a calculation of other fields' values
- [Django]-"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.
- [Django]-Update all models at once in Django
3đź‘Ť
This is not a good idea in general. Do all the logic in python and pass the data to template for displaying. Template should be as simple as possible to ensure those working on the design can focus on design rather than worry about the logic.
To give an example, if you need some derived information within a template, it is better to get it into a variable in the python code and then pass it along to the template.
- [Django]-*_set attributes on Django Models
- [Django]-How can I get MINIO access and secret key?
- [Django]-Django models.py Circular Foreign Key
3đź‘Ť
In your template you can do like this:
{% jump_link as name %}
{% for obj in name %}
<div>{{obj.helo}} - {{obj.how}}</div>
{% endfor %}
In your template-tags you can add a tag like this:
@register.assignment_tag
def jump_link():
listArr = []
for i in range(5):
listArr.append({"helo" : i,"how" : i})
return listArr
- [Django]-VueJS + Django Channels
- [Django]-(13: Permission denied) while connecting to upstream:[nginx]
- [Django]-How to tell if a task has already been queued in django-celery?
3đź‘Ť
Use the with statement.
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
I can’t imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.
- [Django]-Constructing Django filter queries dynamically with args and kwargs
- [Django]-Find object in list that has attribute equal to some value (that meets any condition)
- [Django]-South migration: "database backend does not accept 0 as a value for AutoField" (mysql)