1

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.

Van
  • 302
  • 3
  • 18
  • 1
    Take a look [here](https://stackoverflow.com/questions/1107737/numeric-for-loop-in-django-templates). The range function is not supported by Django template, unfortunately. – Franndy Abreu Nov 06 '18 at 21:51
  • Errrrrg. Thanks, Franndy. – Van Nov 06 '18 at 21:56

1 Answers1

5

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 %}
Van
  • 302
  • 3
  • 18