Using Template Tags and Filters

Tutorial 3 of 5

Using Template Tags and Filters in Django

1. Introduction

Goal

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.

Learning Objectives

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

Prerequisites

To make the most of this tutorial, you should have:
- Basic understanding of Django framework
- Basic understanding of Python
- Django installed on your machine

2. Step-by-Step Guide

Django Template Tags

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.

Django Template Filters

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.

3. Code Examples

Example 1: Using {% for %} tag

Here 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>

Example 2: Using Filters

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.

4. Summary

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

5. Practice Exercises

Exercise 1: Displaying a List

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>

Exercise 2: Formatting Date

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!