What are Template Tags & Filters in Django?
Django, a high-level Python web framework, is well known for its clean design and ease of use. One of its most powerful features is the templating system, enabling developers to generate HTML dynamically. Django’s template language includes a rich set of built-in template tags and filters, making it easy to manipulate data and create dynamic content.
In this blog post, we’ll explore some of the most useful built-in template tags and filters in Django, providing examples and explaining how to use them effectively.
What are Template Tags and Filters?
Template tags and filters are special syntax elements within Django templates that allow you to perform various operations. Template tags are more like functions or control structures (e.g., loops, conditions), while filters are used to modify the presentation of variables.
Built-in Template Tags
Let’s start by exploring some commonly used built-in template tags.
1. ‘for‘ Tag
The ‘ for ‘ tag is used for iterating over a sequence, such as a list or a queryset. It’s similar to a for loop in Python.
HTML
{% for item in item_list %}
- {{ item }}
{% endfor %}
In this example, ‘item_list’ is a context variable passed to the template. The ‘for’ tag iterates over ‘item_list’, and for each item, it creates an ‘<li>’ element containing the item’s value.
2. ‘if‘ Tag
The ‘ if ‘ tag lets you implement conditional logic in your templates.
HTML
{% if user.is_authenticated %}
Welcome, {{ user.username }}!
{% else %}
Please log in.
{% endif %}
Here, the template checks if the user is authenticated. If true, it displays a welcome message with the user’s username; otherwise, it prompts the user to log in.
3. ‘block’ and ‘extends’ Tags
These tags facilitate template inheritance, a robust feature that lets you create a base template and extend it in other templates.
HTML
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header>
<h1>{% block header %}Welcome to My Site{% endblock %}</h1>
</header>
<ul>
{% for item in item_list %}
<li>
{% if item.description %}
{{ item.description|truncatechars:50 }}
{% else %}
No description available
{% endif %}
</li>
{% endfor %}
</ul>
<main>
{% block content %}{% endblock %}
</main>
<footer>
{% block footer %}(c) 2023 My Site{% endblock %}</footer>
</body>
</html>
HTML
<!-- home.html -->
{% extends "base.html" %}
{% block title %}Home - My Site{% endblock %}
{% block header %}Welcome to the Home Page{% endblock %}
{% block content %}
<p>This is the home page content.</p>
{% endblock %}
In this example, ‘home.html’ extends ‘base.html’, overriding the ‘title’ , ‘header’, and ‘content’ blocks to provide specific content for the home page.
4. ‘url’ Tag
The ‘url’ tag is used to reverse-resolve URLs. It’s especially useful for generating URLs dynamically, ensuring that your URLs are always up-to-date.
HTML
<a href="{% url 'app_name:view_name' %}">Link to View</a>
Here, “ ‘app_name:view_name’ “ is the name of the URL pattern you want to resolve. Django will replace it with the actual URL path.
Built-in Template Filters
Filters are used to modify the value of variables before they are displayed. Let’s look at some common built-in filters.
1. ‘date’ Filter
The ‘date’ filter formats a date or datetime object according to a given format string.
HTML
{{ user.date_joined|date:"F j, Y" }}
If ‘user.date_joined’ is a date or datetime object, this filter will format it as “January 1, 2023”.
2. ‘length’ Filter
The ‘length’ filter returns the number of items in a list or the length of a string.
HTML
Number of items: {{ item_list|length }}
This will display the number of items in ‘item_list’.
3. ‘default’ Filter
The ‘default’ filter provides a default value if the variable is undefined or empty.
HTML
{{ user.bio|default:"No bio available" }}
If ‘user.bio’ is empty, this will display “No bio available”.
4. ‘truncatechars’ Filter
The ‘truncatechars’ filter truncates a string to a specified number of characters.
HTML
{{ post.content|truncatechars:100 }}
This will truncate ‘post.content’ to 100 characters, appending “…” if the content is longer.
Combining Template Tags and Filters
You can combine template tags and filters to create more complex templates. For example:
HTML
{% for item in item_list %}
-
{% if item.description %}
{{ item.description|truncatechars:50 }}
{% else %}
No description available
{% endif %}
{% endfor %}
This template iterates over ‘item_list’, checks if each ‘item’ has a ‘description’, and truncates it to 50 characters if it exists. Otherwise, it displays a default message.
Custom Template Tags and Filters
In addition to built-in tags and filters, Django allows you to create custom template tags and filters to suit your specific needs.
How to Create a Custom Filter
To create a custom filter, add a ‘templatetags’ directory to your app, create a Python file (e.g., custom_filters.py), and register your filter.
Python
# myapp/templatetags/custom_filters.py
from django import template
register = template.Library()
@register.filter(name='multiply')
def multiply(value, arg):
return value * arg
Load and use the custom filter in your template:
HTML
{% load custom_filters %}
{{ 5|multiply:3 }}
Creating a Custom Tag
Similarly, you can create a custom tag. For example, a simple tag that returns the current time:
Python
# myapp/templatetags/custom_tags.py
from django import template
import datetime
register = template.Library()
@register.simple_tag
def current_time(format_string):
return datetime.datetime.now().strftime(format_string)
Load and use the custom tag in your template:
HTML
{% load custom_tags %}
Current time: {% current_time "%Y-%m-%d %H:%M:%S" %}
Best Practices for Using Template Tags & Filters
- Keep Logic in Views: Avoid placing complex logic in templates. Use views to process data and pass it to templates.
- Use Built-in Tags and Filters: Before creating custom tags or filters, check if built-in options can achieve the same result.
- Maintain Readability: Use template tags and filters to enhance the readability and maintainability of your templates.
- Use Template Inheritance: Leverage template inheritance to avoid redundancy and keep your templates DRY (Don’t Repeat Yourself).
To read more about building dynamic web applications with Django templates, refer to our blog How to Build Dynamic Web Applications with Django Templates
Conclusion
Django’s built-in template tags and filters provide powerful tools for dynamically generating HTML and manipulating data in templates. By understanding and utilizing these features, you can create flexible and maintainable templates that enhance the user experience. Additionally, custom tags and filters allow you to extend Django’s templating capabilities to meet your specific requirements. By following best practices and leveraging Django’s templating system, you can build robust and scalable web applications with ease.