← Back to Chapters

Django Template Engine Overview

? Django Template Engine Overview

? Quick Overview

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.

? Key Concepts

  • Separation of logic and presentation
  • Dynamic content rendering using context data
  • Reusable and maintainable HTML templates

? Syntax / Theory

The Django template engine combines templates with context data. Templates contain placeholders called variables and logic blocks called template tags.

? Basic Template Structure

? View Code Example
<!-- Django template with variables -->
<html>
<body>
<h1>Welcome, {{ user_name }}!</h1>
<p>You have {{ num_messages }} new messages.</p>
</body>
</html>

?️ Template Tags

Template tags control logic such as loops and conditionals and are written using {% %}.

  • for – Iterates over data
  • if – Conditional rendering
  • include – Reuse templates
? View Code Example
{% 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 %}

?️ Template Filters

Filters modify variables before display using the pipe (|) operator.

  • lower
  • date
  • length
? View Code Example
{# Applying Django template filters #}
{{ user_name|lower }}
{{ current_date|date:"F j, Y" }}

? Live Output / Explanation

When rendered, template variables are replaced with actual data passed from Django views, producing dynamic HTML output.

? Interactive Example

Try modifying variables like user_name or adding more messages in your Django view to instantly see changes reflected in the template.

 

? Use Cases

  • Rendering dynamic user dashboards
  • Displaying lists like blog posts or comments
  • Creating reusable layout templates

✅ Tips & Best Practices

  • Keep business logic out of templates
  • Use {% include %} for reusable components
  • Organize templates inside templates/app_name/

? Try It Yourself

  • Create a template that lists blog posts dynamically
  • Use for and if tags for conditional display
  • Experiment with filters like lower and date