🎓 A1Learner
🔍
0 of 50 lessons completed

Django Template Variables

A template variable is a named value that a template shows. The {{ }} marks hold the name of the value.

Pass values to the template

The view passes a name and a score. The template file uses both.

def card(request):
    return render(request, "card.html", {"name": "Mara", "score": 9})

Show the values in the file

The file holds one line with two blanks. Each blank names a value.

<p>{{ name }} scored {{ score }}.</p>

Read one part of a value

The view passes one dict named post. The dot reads its title.

def post_page(request):
    return render(request, "post.html", {"post": {"title": "First post"}})

Ask for the page

The test client asks for the page and prints the filled-in page.

from django.test import Client

client = Client()
print(client.get("/card/").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("<p>{{ name }} scored {{ score }}.</p>")
print(template.render(Context({"name": "Mara", "score": 9})))
template = Template("<h1>{{ post.title }}</h1>")
print(template.render(Context({"post": {"title": "First post"}})))

Key points

  • {{ name }} shows the value passed as name.
  • The context is the dict of values passed to a template.
  • Pass every value the template uses in the context.
  • Numbers work in {{ }} like words do.
  • A missing value shows nothing.
  • A dot reads one part of a value, like {{ post.title }}.

In this example, the setup lines configure Django. The program renders a template string with Template and Context. A real project keeps templates in files. The first template shows a name and a score. The second template reads the title out of a dict with a dot. Both prints show the filled-in pages.

Note

Values pass by name, so their order does not matter.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does {{ score }} show when the view passes score=9?