Ruth
Ruth

Reputation: 5816

How to remove an item from a list in the Django template language?

Is there a way to remove an item from a list in the Django template language?

I have a situation where I'm iterating through one list, and printing the first item in another list. Once the first item is printed I want to remove it from that list.

See below:

{% for item in list1 %}
     {{list2.0}}
     #remove list2.0 from list2
{% endfor %}

Upvotes: 6

Views: 11420

Answers (4)

user707650
user707650

Reputation:

If your list1 and list2 are indeed lists and not querysets, this seems to work:

{{ list2 }}  {# show list2 #}
{% for item in list1 %}
    {{ list2.0 }}
    {# remove list2.0 from list2 #}
    {{ list2.pop.0 }}
{% endfor %}
{{ list2 }}  {# empty #}

Note that pop does not return in this case, so you still need {{ list2.0 }} explicitly.

Upvotes: 8

AndrewJesaitis
AndrewJesaitis

Reputation: 482

I would try to filter out the item in the view if at all possible. Otherwise you can add in an if or if not statement inside the for loop.

{% for item in list%}
    {% if item.name != "filterme" %}
        {{ item.name }}
    {% endif %}
{% endfor %}

Upvotes: 2

Konrad Hałas
Konrad Hałas

Reputation: 5144

There is no such built-in template tag. I understand that you don't want to print first item of list2 if list1 is not empty. Try:

{% for item in list1 %}
     {{list2.0}}
     ...
{% endfor %}

{% for item in list2 %}
     {% if list1 and forloop.counter == 1 %}
         # probably pass
     {% else %}
         {{ item }}
     {% endif %}
{% endfor %}

This is not a good idea to manipulate the content of the list in templates.

Upvotes: 0

Delyan
Delyan

Reputation: 8911

You can't delete an item but you can get the list without a certain item (at a constant index)

{% with list2|slice:"1:" as list2 %}
...
{% endwith %}

Of course, nesting rules apply, etc.

In general, I you find yourself doing complex data structure manipulation, just move it to Python - it'd be faster and cleaner.

Upvotes: 0

Related Questions