Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Template Tags in Django

Introduction

In Django, template tags are used to add logic in templates. They help in rendering the dynamic content in the templates. Template tags are used inside curly braces and percent signs {% %}. This tutorial will guide you through various commonly used template tags with examples.

{% for %} Tag

The {% for %} tag is used for iterating over a sequence (like a list or a queryset). It allows you to loop through items and display them.

Example:

{% raw %}
    {% for item in item_list %}
  • {{ item }}
  • {% endfor %}
{% endraw %}

{% if %} Tag

The {% if %} tag is used for conditional statements. It allows you to render content based on certain conditions.

Example:

{% raw %}
{% if user.is_authenticated %}
    

Welcome, {{ user.username }}!

{% else %}

Please log in.

{% endif %} {% endraw %}

{% block %} and {% extends %} Tags

The {% block %} and {% extends %} tags are used for template inheritance. The {% extends %} tag is used in child templates to inherit from a parent template, and the {% block %} tag defines a block that the child template can override.

Example (base.html):

{% raw %}



    
    {% block title %}My Site{% endblock %}


    

My Site

{% block content %} {% endblock %}