🎓 A1Learner
🔍
0 of 50 lessons completed

Django Template Conditions

A template condition hides or shows a block by a test. The {% if %} line opens the condition.

Make the views

Three views share one template. Each one passes different values.

def member_page(request):
    return render(request, "page.html", {"member": True, "visits": 3})

def returning_page(request):
    return render(request, "page.html", {"member": False, "visits": 2})

def guest_page(request):
    return render(request, "page.html", {"member": False, "visits": 0})

The page with a condition

The template tests member first, then visits. Each reader sees one line.

{% if member %}<p>Welcome back!</p>{% elif visits > 0 %}<p>Come back soon.</p>{% else %}<p>Please join.</p>{% endif %}

Ask for the three pages

The test client visits each address and shows the line each reader sees.

from django.test import Client

client = Client()
print(client.get("/member/").content.decode())
print(client.get("/returning/").content.decode())
print(client.get("/guest/").content.decode())

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()

from django.template import Context, Template

template = Template("{% if member %}<p>Welcome back!</p>{% elif visits > 0 %}<p>Come back soon.</p>{% else %}<p>Please join.</p>{% endif %}")
print(template.render(Context({"member": True, "visits": 3})))
print(template.render(Context({"member": False, "visits": 2})))
print(template.render(Context({"member": False, "visits": 0})))

Key points

  • {% if member %} keeps the block when member is true.
  • {% else %} keeps the other block when the test fails.
  • {% elif %} tests a new condition when the first one fails.
  • The block ends with {% endif %}.
  • Conditions keep parts of a page back from some readers.

In this example, the setup lines configure Django. The program renders one template string with three sets of values. A real project keeps templates in files. The first set passes member as true, so the page greets the reader with Welcome back. The second set fails the first test and passes the visits test, so the page says Come back soon. The third set fails both tests, so the else line shows.

Note

The test reads the value passed to the template.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

The template has {% if member %} with an {% else %} block. What shows when member is False?