style="background-color: #D3D3D3;"
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.
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:
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 (
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.