Django Template Language - remove an item from a list

Just a quick question: is there a way to remove an item from a list in the Django template language?

I have a situation where I repeat one list and print the first item in another list. As soon as the first item is printed, I want to remove it from this list.

See below:

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

Thanks in advance.

+5
source share
4 answers

If your list1 and list2 are really lists, not queries, 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 this popdoes not return in this case, so you still need {{list2.0}} explicitly.

+6
source

, . if if not for.

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

You cannot delete an item, but you can get a list without a specific item (with a constant index)

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

Of course, nesting rules apply, etc.

In general, I believe that you are performing complex data manipulations, just move it to Python - it will be faster and cleaner.

0
source

There is no such built-in template tag. I understand that you do not want to print the first element list2if it is list1not 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 %}

It is not recommended to manipulate the contents of the list in templates.

0
source

All Articles