Your First Django Template
A template is a text file with gaps for values. Django fills the gaps and returns the finished page.
A template file
This file holds page text with one gap. The gap is named name.
Hello, {{ name }}!Render it
This line fills the template with Sana and returns the page.
return render(request, "home.html", {"name": "Sana"})Ask for the page
This template holds one gap. The render call fills it with Sana.
template = Template("Hello, {{ name }}!")
print(template.render(Context({"name": "Sana"})))A template with a count
This template holds two gaps. The render call fills both of them.
template = Template("{{ name }} has {{ count }} posts.")
print(template.render(Context({"name": "Sana", "count": 3})))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("Hello, {{ name }}! You have {{ count }} posts.")
print(template.render(Context({"name": "Sana", "count": 3})))Key points
- A template is a file that holds page text with gaps.
- A gap is written in double curly brackets, like {{ name }}.
- The render function fills a template and returns the page.
- Render takes the request, the template name, and the values.
- Values travel to the template inside a dictionary.
In this example, the setup lines grow with the template setting. The setting names the template engine. The template holds two gaps, name and count. The render call fills the gaps with Sana and 3. The print shows the finished page. A real project keeps templates in files. This program renders a template string instead.
Note
A template gap shows nothing when its value is missing.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What fills the gaps in a template?