</>
Skip to content
Django lessons (12/43)

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

VariableDescription
forloop.counterCurrent iteration (1-based)
forloop.counter0Current iteration (0-based)
forloop.revcounterReverse counter
forloop.firstIs first iteration
forloop.lastIs last iteration
forloop.parentloopParent 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

  1. Use if/else/elif conditions
  2. Loop with forloop variables
  3. Include partial templates
  4. 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.