← Back to Chapters

Using Variables, Filters & Template Tags

? Using Variables, Filters & Template Tags

? Quick Overview

Django templates allow you to inject dynamic content and manage logic directly in HTML using variables, filters, and template tags like for, if, and include.

? Key Concepts

  • Variables render dynamic data
  • Filters transform values
  • Template tags control logic and structure

? Syntax / Theory

  • {{ variable }} → Output data
  • {{ variable|filter }} → Modify output
  • {% tag %} → Control logic

? Code Examples

? View Code Example
// Displaying template variables
<h1>Welcome, {{ user_name }}!</h1>
<p>You have {{ num_messages }} new messages.</p>
? View Code Example
// Applying Django template filters
{{ user_name|lower }}
{{ current_date|date:"F j, Y" }}
{{ user_profile|default:"Profile not available" }}
? View Code Example
// Looping with for tag
{% for message in messages %}
<p>{{ message }}</p>
{% endfor %}
? View Code Example
// Conditional rendering with if tag
{% if user_is_authenticated %}
<p>Welcome back, {{ user_name }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
? View Code Example
// Including reusable templates
{% include "header.html" %}

? Live Output / Explanation

Templates dynamically replace placeholders with real data passed from Django views, allowing HTML to respond intelligently to application state.

? Interactive Example

User is not authenticated

? Django Template Simulator

Modify the values below to see how Django syntax renders them.

Browser Render:
 

? Use Cases

  • User dashboards
  • Dynamic lists and tables
  • Reusable layouts

✅ Tips & Best Practices

  • Keep logic minimal inside templates
  • Use filters for clean formatting
  • Reuse templates using include

? Try It Yourself

  • Create a loop with for
  • Add a conditional login message
  • Include a footer template