Basic template-tags and filters

As we've mentioned already, the template system ships with built-in tags and filters. The sections that follow provide a rundown of the most common tags and filters.

Tags

if/else

The {% if %} tag evaluates a variable, and if that variable is True (that is, it exists, is not empty, and is not a false Boolean value), the system will display everything between {% if %} and {% endif %}, for example:

{% if today_is_weekend %} 
    <p>Welcome to the weekend!</p> 
{% endif %} 

An {% else %} tag is optional:

{% if today_is_weekend %} 
    <p>Welcome to the weekend!</p> 
{% else %} 
    <p>Get back to work.</p> 
{% endif %} 

The if tag may also take one or several {% elif %} clauses as well:

{% if athlete_list %} Number of athletes: {{ athlete_list|length ...

Get Mastering Django: Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.