Django’s template engine is a powerful tool for rendering dynamic HTML pages. It allows you to separate the logic of your views from the structure of your HTML. This section provides an overview of Django's template engine, explaining how it works, the syntax it uses, and how it helps generate dynamic web content.
The Django template engine combines templates with context data. Templates contain placeholders called variables and logic blocks called template tags.
<!-- Django template with variables -->
<html>
<body>
<h1>Welcome, {{ user_name }}!</h1>
<p>You have {{ num_messages }} new messages.</p>
</body>
</html>
Template tags control logic such as loops and conditionals and are written using {% %}.
{% for and if template tags example %}
{% for message in messages %}
<p>{{ message }}</p>
{% endfor %}
{% if user_is_authenticated %}
<p>Welcome back!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
Filters modify variables before display using the pipe (|) operator.
{# Applying Django template filters #}
{{ user_name|lower }}
{{ current_date|date:"F j, Y" }}
When rendered, template variables are replaced with actual data passed from Django views, producing dynamic HTML output.
Try modifying variables like user_name or adding more messages in your Django view to instantly see changes reflected in the template.
{% include %} for reusable componentstemplates/app_name/for and if tags for conditional displaylower and date