0

I have a list of 2 dicts

foobar = [ {dict1},
        {dict2}
      ]

Django's docs say that the slice template tag works EXACTLY like python slice.

So I tested in a python shell, and sure enough:

>>> foo = [1,2]
>>> foo[-2]
1

However, when I do this in my template:

{% with foobar|slice:"-2" as previous_thing %}
{{ previous_thing }}

I get an empty list [].

{% with foobar|slice:"1" as previous_thing %} yields what I expect (the first item in the list), as does {{ foobar }} (a list of 2 dicts).

What the heck is going on?!

Colleen
  • 23,899
  • 12
  • 45
  • 75

1 Answers1

3
>>> foo = [1,2]

This is called indexing:

>>> foo[-2]
1

and this is called slicing:

>>> foo[:-2]  #return all items up to -2 index(i.e 0th index), so empty list
[]
>>> foo[:-1]
[1]
>>> foo[:2]
[1, 2]

Slicing works for non-existent indexes as well:

>>> foo[-10000:100000]
[1, 2]

But indexing won't:

>>> foo[100000]
Traceback (most recent call last):
    foo[100000]
IndexError: list index out of range
Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • True, but again `slice:"1"` works. So my question remains open. – Colleen Sep 06 '13 at 18:24
  • 1
    @Colleen What do you mean? `slice:"1"` works because `[1, 2][:1]` returns `[1]` while: `[1, 2][1]` would return `2`. – Ashwini Chaudhary Sep 06 '13 at 18:27
  • 'slice:"1" works because [1, 2][:1]' is what I was looking for. Roughly. (Aka, if you pass an index to the slice template tag, it's going to assume you mean `:index`. (Edit, ahem, duh, exclusive). – Colleen Sep 06 '13 at 18:30
  • @Colleen There's nothing wrong with `foo[:-2]`, it is equivalent to: `foo[:0]`, return all items up to 0th index(not inclusive), as there are no items before 0th index so it returns empty list. – Ashwini Chaudhary Sep 06 '13 at 18:32
  • lol yeah realized the dumb and made the edit as you were typing :P – Colleen Sep 06 '13 at 18:33