This tutorial is designed to guide you on using Django's template tags and filters to create dynamic web content. Template tags and filters provide a powerful way to control how your data is rendered on the page and perform data manipulation right from your templates.
By the end of this tutorial, you will be able to:
- Understand Django's template tags and filters
- Use template tags to control HTML rendering
- Use filters to manipulate data within your templates
To make the most of this tutorial, you should have:
- Basic understanding of Django framework
- Basic understanding of Python
- Django installed on your machine
Template tags give you the ability to add Python logic into your HTML code. The most common tags are {% for %}
and {% if %}
.
Example:
{% if user.is_authenticated %}
Hello, {{ user.username }}.
{% else %}
Please log in.
{% endif %}
In this example, the {% if %}
tag checks if the user is authenticated. If so, it greets the user; otherwise, it prompts the user to log in.
Filters allow you to format and transform your data. They're used within variables using the pipe character (|
).
Example:
{{ user.username|capfirst }}
In this example, the capfirst
filter is used to make sure the first character of the username is capitalized.
{% for %}
tagHere is an example of how you can use the {% for %}
tag to loop over a list of items:
<ul>
{% for item in item_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Here is an example of how you can use filters to format data:
{{ user.date_joined|date:"F j, Y" }}
In this example, the date
filter is used to format the date_joined
field into a more readable format.
In this tutorial, we've learned how to use Django's template tags and filters to control how data is rendered and manipulated in our templates.
To continue learning, you can:
- Explore more Django template tags and filters
- Practice using tags and filters in your own Django projects
Create a list of items and use the {% for %}
tag to display each item.
Solution:
<ul>
{% for item in ['apple', 'banana', 'cherry'] %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Use the date
filter to format the current date in the format 'Y-m-d'.
Solution:
{{ now|date:"Y-m-d" }}
Remember, practice is the key to mastering these concepts. Happy coding!