Template (Django)

A Django template is an HTML file containing Django Template Language tags. Views render it into final HTML by passing a context dictionary, whose keys become variables you display with {{ }} and control with {% %}.

Django

Templates are Django's presentation layer. You write mostly normal HTML and sprinkle in {{ variable }} to insert data and {% tag %} to add logic like loops and conditionals. The view supplies a context dict, and Django substitutes the values.

Django ships its own template engine (the Django Template Language), deliberately limited to discourage business logic in templates; for example you cannot call functions with arguments. Many projects also use Jinja2, which Django supports as an alternative engine.

Templates live in a templates/ directory, either per app (templates/appname/) or in a project-wide DIRS path. Template inheritance with {% extends %} and {% block %} is the main way to share a common page layout.

Syntax

{{ variable }}   {% for x in items %}...{% endfor %}

Examples

Python

<!-- templates/post.html -->
<h1>{{ post.title }}</h1>
{% if post.published %}
  <p>{{ post.body }}</p>
{% else %}
  <p>Draft</p>
{% endif %}

Learn it in a lesson

See also

Back to the Dictionary