Search code examples
pythondjangodictionarydjango-templatesiteration

Is there any way to know when I'm passed the last item while iterating through a dictionary in django template?


I'm trying to create a text representation of a JSONField that has some data structured as an array of dictionaries like this:

[
 {
  "key1":"value1",
  "key2":"value2"
 },
 {
  "key3":"value3",
  "key4":"value4",
  "key5":"value5"
 }
]

My goal is to represent this data in the Django template like this:

( key1=value1 & key2=value2 ) || ( key3=value3 & key4=value4 & key5=value5 )

Now I'd iterate through the array and see if I'm not hitting the last dictionary so I can add an || between the condition representation text since it's already an array list like:

{% for dict in data %}
 // Do stuff with dict
 {% if data|last != dict %}
  ||
 {% endif %}
{% endfor %}

However, since a dictionary doesn't have a last thing, I'm having a hard time to iterate through the "key,value" when I'm doing stuff with each dictionary object when I've got to append an "&" only if I'm not hitting the end of this dict items.

{% for k,v in dict %}
 k=v
 // append "&" if this is not the last key being iterated?
{% endfor %}

Any suggestions/workarounds/ideas would be much appreciated :)


Solution

  • Just found it! Silly me, Seems like Django already provides a pretty neat built-in forloop object for templates that works like a charm!

    Will drop it here for anyone who might have the same problem

    {% for k,v in dict %}
     k=v
     {% if forloop.last != True %}
     &
     {% endif %}
    {% endfor %}