Back to Python
2026-02-106 min read

Tags (Python Programming)

Learn Tags (Python Programming) step by step with clear examples and exercises.

Title: Mastering Dynamic Web Pages with Python Template Tags - A full guide

Why This Matters

In web development, templates allow you to create dynamic and reusable web pages. Python's template tags provide a powerful way to manipulate data within your HTML templates, making it easier to generate customized content for each user or situation. Understanding Python template tags is essential for building scalable and efficient web applications.

By learning Python template tags, you will be able to:

  • Dynamically generate personalized content based on user input or data from a database
  • Simplify repetitive tasks in your HTML templates using loops and conditional statements
  • Apply filters to modify the appearance of text and other elements
  • Secure your web application by properly escaping user-provided data

Prerequisites

To follow this tutorial, you should have a basic understanding of:

  • Python programming concepts, such as variables, functions, and loops
  • HTML and CSS basics
  • Familiarity with the Django web framework (optional but recommended)

Before diving into template tags, it's essential to have a good grasp of these prerequisites. If you are new to Python or Django, consider reviewing the following resources:

Core Concept

Python template tags are special syntax used within your HTML templates to perform various operations on data. They enable you to dynamically generate content based on Python code, making your web pages more interactive and personalized.

Django, a popular Python web framework, provides a rich set of built-in template tags for handling common tasks such as loops, conditional statements, and filters. In this tutorial, we will focus on some essential Django template tags to help you get started with creating dynamic web pages using Python.

Loops

Django's {% for %} loop allows you to iterate over a list or queryset within your HTML templates. This is useful when you need to generate multiple HTML elements based on data, such as displaying a list of items.

{% for item in my_list %}
<p>{{ item }}</p>
{% endfor %}

Advanced Loop Techniques

  • Using the with keyword to access the loop counter:
{% for i, item in my_list %}
<p>Item {{ i }} - {{ item }}</p>
{% endfor %}
  • Looping through dictionaries:
{% for key, value in my_dict.items %}
<p>Key: {{ key }} Value: {{ value }}</p>
{% endfor %}

Conditional Statements

The {% if %} conditional statement lets you check if a condition is true and execute different HTML based on the result. This can help you create personalized content for users or display error messages when necessary.

{% if user.is_staff %}
<p>Welcome, admin!</p>
{% else %}
<p>Hello, guest!</p>
{% endif %}

Advanced Conditional Techniques

  • Using the {% elif %} statement to check multiple conditions:
{% if user.is_staff %}
<p>Welcome, admin!</p>
{% elif user.is_superuser %}
<p>Welcome, superuser!</p>
{% else %}
<p>Hello, guest!</p>
{% endif %}
  • Using the {% with %} tag to set a variable within the conditional block:
{% if user.is_staff %}
{% with user.get_full_name as name %}
<h1>Welcome, {{ name }}!</h1>
{% endwith %}
{% else %}
<p>Hello, guest!</p>
{% endif %}

Filters

Filters allow you to modify the appearance or behavior of text and other elements within your HTML templates. Django provides a variety of built-in filters for tasks such as truncating text, converting text to uppercase or lowercase, and formatting dates.

<p>{{ my_text|uppercase }}</p> <!-- Converts the text to uppercase -->
<p>{{ post.publish_date|date:"F d, Y" }}</p> <!-- Formats the date as "Month day, Year" -->

Advanced Filter Techniques

  • Combining filters:
<p>{{ my_text|uppercase|truncatewords:10 }}</p> <!-- Truncates text to 10 words and converts the rest to uppercase -->
  • Creating custom filters:

To create a custom filter, write a custom template tag library and register it with Django. For more information, refer to the Django documentation.

Worked Example

Let's create a simple example of using Django template tags to display a list of items in an HTML template. First, make sure you have Django installed and set up correctly. For this example, we will use the django.template library directly.

  1. Create a new Python file called templates/example_tags.html with the following content:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example Template Tags</title>
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
<h1>List of Items</h1>
{% for item in my_list %}
<p>{{ item }}</p>
{% endfor %}
</body>
</html>
  1. Create a new Python file called example_tags.py within the same directory as your settings.py file:
from django.http import HttpResponse

items = ['Apple', 'Banana', 'Cherry']

def example_tags(request):
return HttpResponse(open('example_tags.html').read())
  1. Add the following lines to your settings.py file:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
}
]
  1. Run your Django development server and navigate to the URL where your example template is located (e.g., http://localhost:8000/example_tags/). You should see a web page displaying the list of items.

Common Mistakes

  1. Forgetting to load the static files in the HTML template:
{% load static %} <!-- Missing this line will cause static files (CSS, images) not to be loaded properly -->
  1. Using an incorrect template tag or syntax:
  • Make sure you use the correct tag name and that it is written in lowercase (e.g., {% for %} instead of {% FOR %}).
  • Ensure that the tag is closed with its corresponding endtag (e.g., {% endfor %} after a {% for %} loop).
  1. Not escaping user-provided data:

When displaying user-supplied data, it's essential to escape the content to prevent potential security risks such as Cross-Site Scripting (XSS) attacks. Use the |safe filter when necessary:

{% autoescape off %}
<p>{{ user_input|safe }}</p>
{% endautoescape %} <!-- Turns off automatic HTML escaping for this block -->
  1. Improper use of loops and conditional statements:
  • Make sure you initialize your variables before using them in loops or conditionals.
  • Be aware that loops and conditionals can only be used within template tags (e.g., {% %}).
  1. Misusing filters:
  • Use the correct filter for the desired output. For example, use |truncate to truncate text instead of |uppercase.
  • Be aware that some filters may not work as expected when combined with other filters or within loops.

Practice Questions

  1. Use a {% if %} conditional statement to display a message if a variable is_admin is True.
  2. Create a simple loop that displays the numbers 1 through 5 using a {% for %} loop.
  3. Add a filter to uppercase all text within an HTML paragraph tag (``).
  4. Use the {% url %} template tag to create a link to another view called about.

FAQ

Q: What happens if I forget to close a loop or conditional statement?

A: If you forget to close a loop or conditional, Django will raise an error when rendering the template.

Q: Can I create my own custom template tags in Python?

A: Yes, you can create your own custom template tags by writing a custom template tag library and registering it with Django.

Q: How do I escape user-provided data to prevent XSS attacks?

A: Use the |safe filter when displaying user-supplied data or turn off automatic HTML escaping using the {% autoescape off %} and {% autoescape on %} tags.

Q: How do I use filters within loops to apply the same filter to multiple items?

A: Apply the filter to each item individually within the loop, like so:

{% for item in my_list %}
<p>{{ item|uppercase }}</p>
{% endfor %}
Tags (Python Programming) | Python | XQA Learn