style="background-color: #D3D3D3;" Understanding Django Tags: Best Practices and Examples | Q3 Schools


Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Django Template Tags


What Are Template Tags?

Template tags in Django are used to perform operations within a template. They can do various things like:

Template tags are surrounded by {% ... %} syntax, distinguishing them from regular template variables, which use {{ ... }} syntax.

Common Template Tags

Here are some common Django template tags and how to use them.

1. if Tag

The if tag lets you include conditional logic in your templates. It's similar to if statements in programming languages:

{% if user.is_authenticated %}

Welcome, {{ user.username }}!

{% else %}

Please log in.

{% endif %}

In this example, the content inside the if block is displayed if the user is authenticated. Otherwise, the content in the else block is shown.

2. for Tag

The for tag allows you to loop over a list of items. This is useful when you have a list of objects and you want to display each one:

<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>

In this example, the for tag loops over the items list and creates a list item (

  • ) for each element.

    3. block and extends Tags

    These tags are used for template inheritance, allowing you to create a base template and extend it with additional templates. This is useful for reusing common layouts.

    <!-- child.html -->
    {% extends 'base.html' %} <!-- Indicate the base template to extend -->
    {% block content %} <!-- Override the 'content' block -->
    <p>This is content from the child template.</
    p>
    {% endblock %}

    In this example, the block tag defines a section in the base template that can be overridden, and the extends tag in the child template specifies which base template to use.


  • Advertisement





    Q3 Schools : India


    Online Complier

    HTML 5

    Python

    java

    C++

    C

    JavaScript

    Website Development

    HTML

    CSS

    JavaScript

    Python

    SQL

    Campus Learning

    C

    C#

    java