Django — Template Syntax
If/Else/Elif
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% elif user.is_anonymous %}
<p>Please log in.</p>
{% else %}
<p>Guest user</p>
{% endif %}
For Loop
{% for post in posts %}
<h2>{{ forloop.counter }}. {{ post.title }}</h2>
{% if forloop.first %}<p>First post!</p>{% endif %}
{% if forloop.last %}<p>Last post!</p>{% endif %}
{% empty %}
<p>No posts available.</p>
{% endfor %}
For Loop Variables
| Variable | Description |
|---|---|
| forloop.counter | Current iteration (1-based) |
| forloop.counter0 | Current iteration (0-based) |
| forloop.revcounter | Reverse counter |
| forloop.first | Is first iteration |
| forloop.last | Is last iteration |
| forloop.parentloop | Parent loop |
Include Tag
{% include 'partials/navbar.html' %}
{% include 'partials/sidebar.html' with title="Sidebar" %}
URL Tag
<a href="{% url 'post_detail' pk=post.pk %}">Read More</a>
<a href="{% url 'home' %}?page=2">Page 2</a>
With Tag
{% with total=items|length %}
<p>Total items: {{ total }}</p>
{% endwith %}
Mini Practice
- Use if/else/elif conditions
- Loop with forloop variables
- Include partial templates
- Use the with tag for variables
Up Next
Continue with Models — database models in Django.
Related Topics
Frequently Asked Questions about Template Syntax
What is Template Syntax in Django?
Template Syntax is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Template Syntax?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Template Syntax.
Why is Template Syntax important in Django?
Template Syntax is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.