Flask Jinja2 Control Structures


What are control structures in Jinja2?

Control structures in Jinja2 are used to add logic to your templates, allowing you to control the flow of rendering based on conditions or iterations. Common control structures include loops ({% for %}), conditionals ({% if %}), and template inheritance ({% extends %} and {% block %}).


How do you use the {% if %} statement in Jinja2?

The {% if %} statement in Jinja2 is used to conditionally render content based on whether an expression evaluates to true. It can be followed by {% elif %} and {% else %} for additional conditional branches.

Example of using the {% if %} statement:

{% if user %}
    <p>Hello, {{ user }}!</p>
{% else %}
    <p>Hello, Guest!</p>
{% endif %}

In this example, the template checks if a user variable is provided and displays a personalized greeting if it exists; otherwise, it shows a generic greeting for a guest.


How do you use the {% for %} loop in Jinja2?

The {% for %} loop in Jinja2 is used to iterate over a list, dictionary, or any other iterable. It allows you to render content for each item in the iterable.

Example of using the {% for %} loop:

<ul>
{% for item in items %}
    <li>{{ item }}</li>
{% endfor %}
</ul>

In this example, the loop iterates over the items list and generates a <li> element for each item in the list.


How do you access loop variables in a Jinja2 {% for %} loop?

Inside a {% for %} loop, Jinja2 provides special loop variables that allow you to access information about the current iteration. Common loop variables include:

  • loop.index: 1-based index of the current iteration.
  • loop.index0: 0-based index of the current iteration.
  • loop.revindex: 1-based index of the current iteration from the end.
  • loop.revindex0: 0-based index of the current iteration from the end.
  • loop.first: True if this is the first iteration.
  • loop.last: True if this is the last iteration.

Example of using loop variables:

<ul>
{% for item in items %}
    <li>{{ loop.index }}. {{ item }}</li>
{% endfor %}
</ul>

In this example, the loop.index variable is used to display the 1-based index of each item in the list.


How do you break or continue a loop in Jinja2?

In Jinja2, you can use the {% break %} and {% continue %} statements to control the flow of a {% for %} loop. {% break %} stops the loop, and {% continue %} skips the current iteration and moves to the next one.

Example of using {% break %} and {% continue %}:

<ul>
{% for item in items %}
    {% if item == "skip" %}
        {% continue %}
    {% elif item == "stop" %}
        {% break %}
    {% endif %}
    <li>{{ item }}</li>
{% endfor %}
</ul>

In this example, the loop skips over any items that are equal to "skip" and stops completely if it encounters an item equal to "stop".


How do you use {% else %} with {% for %} loops in Jinja2?

Jinja2 allows you to use an {% else %} block with a {% for %} loop. The {% else %} block is executed if the loop does not iterate over any items, i.e., if the list is empty.

Example of using {% else %} with a {% for %} loop:

<ul>
{% for item in items %}
    <li>{{ item }}</li>
{% else %}
    <p>No items found.</p>
{% endfor %}
</ul>

In this example, if the items list is empty, the {% else %} block is executed, and the message "No items found" is displayed.


How do you use the {% with %} statement in Jinja2?

The {% with %} statement in Jinja2 allows you to define and use temporary variables within a specific block of code. This is useful for improving readability and reducing redundancy.

Example of using the {% with %} statement:

{% with name = "John", age = 30 %}
    <p>Name: {{ name }}</p>
    <p>Age: {{ age }}</p>
{% endwith %}

In this example, the variables name and age are defined inside the {% with %} block and used within that block.


How do you use the {% block %} and {% extends %} statements in Jinja2?

The {% block %} and {% extends %} statements are used for template inheritance in Jinja2. The {% block %} statement defines a block of content that can be overridden by child templates, while the {% extends %} statement is used to inherit a base template.

Example of a base template (base.html):

<html>
<head>
    <title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

Example of extending the base template:

{% extends "base.html" %}

{% block title %}Home Page{% endblock %}

{% block content %}
    <h1>Welcome to the Home Page</h1>
{% endblock %}

In this example, the child template overrides the title and content blocks defined in the base template.


How do you use the {% include %} statement in Jinja2?

The {% include %} statement in Jinja2 allows you to include the contents of another template within the current template. This is useful for reusing common components like headers, footers, or navigation bars across multiple templates.

Example of using the {% include %} statement:

<html>
<body>
    {% include "navbar.html" %}
    <h1>Main Content</h1>
    {% include "footer.html" %}
</body>
</html>

In this example, the navbar.html and footer.html templates are included within the main template.


What is the {% set %} statement in Jinja2?

The {% set %} statement in Jinja2 allows you to assign values to variables within your templates. This is useful for defining variables that are used multiple times within the same template or for performing calculations.

Example of using the {% set %} statement:

{% set total = price * quantity %}
<p>Total Price: {{ total }}</p>

In this example, the set statement calculates the total price by multiplying the price and quantity variables and assigns it to the total variable, which is then displayed.


How do you use the {% filter %} statement in Jinja2?

The {% filter %} statement in Jinja2 applies a filter to a block of content, rather than just a single variable. This is useful when you want to apply the same filter to multiple lines of content at once.

Example of using the {% filter %} statement:

{% filter upper %}
    <p>This will be uppercase.</p>
    <p>So will this.</p>
{% endfilter %}

In this example, the upper filter is applied to the entire block of content, converting both paragraphs to uppercase.


What is the {% macro %} statement in Jinja2?

The {% macro %} statement in Jinja2 allows you to define reusable template functions (macros) that can be called with arguments. Macros are useful for creating reusable HTML elements, such as form fields or buttons.

Example of defining and using a macro:

{% macro input_field(name, placeholder) %}
    <input type="text" name="{{ name }}" placeholder="{{ placeholder }}">
{% endmacro %}

{{ input_field('username', 'Enter your username') }}

In this example, the input_field macro is defined to generate a text input field with a name and placeholder. It is then called with specific arguments to render the input element.

Ads