[Fixed]-Django template for loop


If your separator is always " " and category is a string, you don’t actually need a custom template filter. You could simply call split with no parameters:

{% for icon in instance.category.split %}
  <p>{{ icon }}</p>
{% endfor %}


You are passing a string instance.category into the template and then iterating over its chars.

Instead, pass a list to the template: instance.category.split() which will split your words words words string into the list ['words', 'words', 'words']:

>>> s = "words words words"
>>> s.split()
['words', 'words', 'words']

Or, you can define a custom filter that will split a string into the list:

from django import template
register = template.Library()

def split(s, splitter=" "):
    return s.split(splitter)

Then, use it in the template this way:

{% for icon in instance.category|split %}
    <p>{{ icon }}</p>
{% endfor %}


I know this is a late answer, but it might help someone (it was the problem I had).
If you have a point in the form: (x, y). then you need:

{% for x, y in points %}
    There is a point at {{ x }},{{ y }}
{% endfor %}

And for key-value pairs:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

source: here (check the for section)


Leave a comment