Skip to the content.

Jinja is a templating engine for Python, used primarily in web development to create dynamic HTML pages, though it can also be used for other templating needs. It allows you to use expressions, variables, and control structures in templates, which are rendered with data provided by Python code.

1. Lists and Python Functions

2. Jinja Filters

In Jinja, filters are used to transform data in templates. You can pass data through filters using the pipe | operator. They are similar to functions in that they take an input, modify it, and return an output.

  {{ my_list | length }}  # Outputs 4 if my_list is [1, 2, 3, 4]

3. Functions or Methods

4. groupby("producer"): Grouping in Jinja

The groupby filter in Jinja allows you to group a list of dictionaries by a common key, such as producer in this case. This filter works similarly to SQL's GROUP BY clause. It groups data based on a shared value and returns a grouper object.

Example:

Assume you have a list of dictionaries representing movies, each having a producer key:

{% set movies = [
    {"title": "Movie A", "producer": "Producer 1"},
    {"title": "Movie B", "producer": "Producer 2"},
    {"title": "Movie C", "producer": "Producer 1"},
    {"title": "Movie D", "producer": "Producer 2"}
] %}

You can group the list by producer using groupby:

{% for producer, group in movies | groupby("producer") %}
  <h2>{{ producer }}</h2>
  <ul>
    {% for movie in group %}
      <li>{{ movie.title }}</li>
    {% endfor %}
  </ul>
{% endfor %}

Output:

Producer 1
- Movie A
- Movie C

Producer 2
- Movie B
- Movie D

Summary: