liveBook · Manning

If tag

As explained in Django in Action

An if tag is a Django template instruction that conditionally renders its enclosed block according to a Boolean condition.

An if tag conditionally renders a block in a Django template. The paired {% if %} and {% endif %} tags evaluate a condition and include the enclosed output only when that condition is true. section 3.2 section 3.5.1

A simple variable condition uses Python-like truthiness: zero, False, empty containers, and missing context variables hide the block; other values show it. section 3.5.1

Use the tag for increasingly specific template decisions:

  • Compare variables or values with ==, !=, <, >, <=, >=, in, not in, is, and is not. section 3.5.1
  • Combine conditions with and, or, and not; and takes precedence over or, following Python’s ordering. section 3.5.1
  • Add {% elif %} for additional tests and {% else %} for the fallback branch. section 3.5.1

Showing a RiffMates welcome heading

The template displays the heading only when first_page is truthy: {% if first_page %} <h1>Welcome to <i>RiffMates</i></h1> {% endif %} A missing first_page value behaves like False, so the heading is omitted rather than causing this block to render. section 3.5.1

{% if first_page %}
    <h1> Welcome to <i>RiffMates</i> </h1>
{% endif %}

Inspect the complete conditional listing for the RiffMates welcome heading. section 3.5.1

How Django in Action covers it

How deep it goes
Explains truthiness, comparisons, Boolean combinations, precedence, and alternative branches, but stops short of custom tag implementation.
Examples
Uses welcome headings, optional page titles, drummer warnings, venue choices, and band-size classifications.
What it assumes
Assumes basic template variables and context values while teaching conditional rendering through familiar Python behavior.
What you can do after
Apply it to show or hide Django template output using truthiness, comparisons, combined conditions, and fallback branches.
How it connects
Connects template variables and context dictionaries with Python-style if statements, comparisons, Boolean operators, and filters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.