Search code examples
django-templatesjinja2

Jinja / Django for loop range not working


I'm building a django template to duplicate images based on an argument passed from the view; the template then uses Jinja2 in a for loop to duplicate the image.

BUT, I can only get this to work by passing a list I make in the view. If I try to use the jinja range, I get an error ("Could not parse the remainder: ...").

Reading this link, I swear I'm using the right syntax.

template

{% for i in range(variable) %}
    <img src=...>
{% endfor %}

I checked the variable I was passing in; it's type int. Heck, I even tried to get rid of the variable (for testing) and tried using a hard-coded number:

{% for i in range(5) %}
    <img src=...>
{% endfor %}

I get the following error:

Could not parse the remainder: '(5)' from 'range(5)'

If I pass to the template a list in the arguments dictionary (and use the list in place of the range statement), it works; the image is repeated however many times I want.

What am I missing? The docs on Jinja (for loop and range) and the previous link all tell me that this should work with range and a variable.


Solution

  • Soooo.... based on Franndy's comment that this isn't automatically supported by Django, and following their link, which leads to this link, I found how to write your own filter.

    Inside views.py:

    from django.template.defaulttags import register
    
    @register.filter
    def get_range(value):
        return range(value)
    

    Then, inside template:

    {% for i in variable|get_range %}
        <img src=...>
    {% endfor %}