The Django Template Engine is a system that allows developers to define dynamically generated HTML responses by combining static HTML structure with dynamic data using a specialized templating language.
Views fetch data, but they shouldn’t contain HTML strings directly (that gets messy). Templates are HTML files with special placeholders and logic tags. Django takes the template, injects the data from the view, and renders a final, standard HTML page to send to the browser.
- A view function gathers context data (a Python dictionary).
- The view calls
render()passing the request, template name, and context. - The template engine reads the HTML file.
- It replaces variables
{{ var }}with actual data. - It executes tags
{% if %},{% for %}to control flow. - Generates final HTML string.
graph LR A[View Context Data] --> C(Template Engine) B[Template HTML File] --> C C --> D[Final HTML Output]
A template is like a form letter (mad libs). The structure of the letter is static, but there are blank spaces for “Name”, “Date”, and “Amount”. The Template Engine is the secretary who takes a list of names and fills out the blank spaces to create individualized letters.
<!-- template.html -->
<h1>Welcome, {{ user.name }}!</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>- Uses
{{ }}for variables and{% %}for tags. - Supports template inheritance (DRY principle).
- Intentionally restricts execution of arbitrary Python code to enforce separation of logic and presentation.
- Built from: Django View — views render templates.
- Related: Django Web Framework — the built in UI layer.
- Related: Django App — templates are usually stored in app directories.
- Related: Django REST Framework — an alternative to templates when building APIs.
- Complex business logic should not reside in templates. If it requires complex filtering or calculation, do it in the View or Model.