Template Tags and Filters

18-Jan-2024

Effortlessly leverage Django template tags and filters with our quick guide. Learn to enhance the presentation and functionality of your web pages for a polished user experience.

Introduction

Django templates come equipped with a robust system of tags and filters, offering powerful tools to manipulate and display data in a flexible manner. This documentation provides insights into the effective use of template tags and filters.


Template Tags

Looping through Data


{% for item in items %}

{{ item }}

{% endfor %}


The {% for %} tag facilitates the iteration through lists or querysets, displaying each item within the loop.


Conditional Statements

{% if condition %}

<p>This is displayed if the condition is true.</p>

{% else %}

<p>This is displayed if the condition is false</p>

{% endif %}

The {% if %} tag allows the inclusion of conditional statements within templates.


Including Other Templates

{% include 'header.html' %}

The {% include %} tag enables the incorporation of the content from another template into the current one.



Template Filters

String Filters

{{ variable|lower }}

The 'lower' filter converts a string to lowercase. Additional string filters include 'upper', 'capfirst', and 'title'.

Date Formatting


{{ date_variable|date:"F d, Y" }}

The `date` filter facilitates the formatting of date and time variables in a human-readable manner.


Numerical Filters

{{ number_variable|add:5 }}

The 'add' filter allows basic arithmetic operations on numerical variables.


Combining Tags and Filters

{% for item in items %}

<p>{{ item.name|title }} - {{ item.price|currency }}</p>

{% endfor %}


In this example, the 'title' filter capitalizes the name, while the 'currency' filter formats the price accordingly.

Comments