0
0
Djangoframework~5 mins

Template tags (if, for, block, extends) in Django

Choose your learning style9 modes available
Introduction

Template tags help you control what shows on a webpage by adding logic inside HTML. They let you repeat parts, check conditions, and organize templates.

Show different messages based on user login status.
Display a list of items like blog posts or products.
Create a base page layout and reuse it for many pages.
Change parts of a page depending on data values.
Loop through data to build tables or menus.
Syntax
Django
{% if condition %}
  ...
{% elif other_condition %}
  ...
{% else %}
  ...
{% endif %}

{% for item in list %}
  ...
{% empty %}
  ...
{% endfor %}

{% block block_name %}
  ...
{% endblock %}

{% extends "base.html" %}

Template tags are inside {% and %} and control logic or structure.

Use {% endtag %} to close tags like if, for, and block.

Examples
Shows a welcome message if the user is logged in, otherwise asks to log in.
Django
{% if user.is_authenticated %}
  <p>Welcome back!</p>
{% else %}
  <p>Please log in.</p>
{% endif %}
Loops over products to list them. Shows a message if the list is empty.
Django
{% for product in products %}
  <li>{{ product.name }}</li>
{% empty %}
  <li>No products found.</li>
{% endfor %}
Defines a block named 'content' that child templates can replace.
Django
{% block content %}
  <h1>Page Title</h1>
  <p>Page content here.</p>
{% endblock %}
Uses the base.html template as a starting point to build the current page.
Django
{% extends "base.html" %}
Sample Program

This template extends a base layout. It shows a list of products or a message if none exist. It also shows a message depending on whether the user is staff or not.

Django
{% extends "base.html" %}

{% block content %}
  <h2>Products</h2>
  <ul>
  {% for product in products %}
    <li>{{ product.name }} - ${{ product.price }}</li>
  {% empty %}
    <li>No products available.</li>
  {% endfor %}
  </ul>

  {% if user.is_staff %}
    <p>You have admin access.</p>
  {% else %}
    <p>Welcome, customer!</p>
  {% endif %}
{% endblock %}
OutputSuccess
Important Notes

Always close your tags with {% endif %}, {% endfor %}, or {% endblock %} to avoid errors.

Use {{ variable }} to show data inside templates.

Template inheritance with {% extends %} helps keep your site consistent and easier to maintain.

Summary

Template tags let you add logic like conditions and loops inside HTML.

Use {% if %} to show content based on conditions, {% for %} to repeat content, {% block %} to define replaceable sections, and {% extends %} to reuse layouts.

They make your web pages dynamic and organized.