Skip to content

Using append and remove to Manipulate Lists in Jinja

In Jinja, lists can be dynamically manipulated during template rendering using the append and remove methods. These methods allow you to add or remove elements from lists, enabling advanced data manipulation directly within your templates.

Adding Entries to a List: Using append

The append method is used to add items to an existing list. This is especially useful when iterating through data and conditionally populating a list based on specific criteria.

Input data

json
{
    "context": {
        "fruits": ["apple", "banana", "cherry", "date"],
        "unwantedFruit": "cherry"
    }
}

Template

jinja
{% set finalFruits = [] %}


{% for fruit in context.fruits %}
    {% if fruit != context.unwantedFruit %}
        {% set _ = finalFruits.append(fruit) %}
    {% endif %}
{% endfor %}


{{ finalFruits }}

Output

json
["apple", "banana", "date"]

Using remove to Filter a List

Using the same input context, we can obtain the same result by using the remove filter

Input Context

json
{
    "context": {
        "fruits": ["apple", "banana", "cherry", "date"],
        "unwantedFruit": "cherry"
    }
}

Template

jinja
{% set filteredFruits = context.fruits %}


{% for fruit in context.fruits %}
    {% if fruit == context.unwantedFruit %}
        {% set _ = filteredFruits.remove(fruit) %}
    {% endif %}
{% endfor %}


{{ filteredFruits }}

Output

json
["apple", "banana", "date"]

Explanation:

  • Initialize the List:
jinja
{% set filteredFruits = context.fruits %}

Start with the original list from the context.

  • Iterate Through the List:
jinja
{% for fruit in context.fruits %}
  • Apply a Condition:
jinja
{% if fruit == context.unwantedFruit %}

Remove the unwantedFruit from the list.

  • Remove the Element:
jinja
{% set _ = filteredFruits.remove(fruit) %}
  • Output the Result:
jinja
{{ filteredFruits }}

Key Notes

  • Initialization:
    • Always initialize your list before appending or removing elements.
    • Example: {% set myList = [] %}.
  • Avoid Modifying During Iteration:
    • If modifying the original list, use a copy or carefully plan the logic.
  • Use Descriptive Variable Names:
    • Clearly name your lists for better readability (e.g., filteredFruits, finalFruits).

Exercise: Practice append and remove

  • Use the provided context data and templates in the Template Playground.
  • Experiment by changing the favoriteFruit or unwantedFruit values.
  • Observe how the list is built or modified during iterations.