Jinja / Django for loop range not working

人走茶凉 提交于 2019-12-08 09:45:18

问题


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.


回答1:


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 %}


来源:https://stackoverflow.com/questions/53180287/jinja-django-for-loop-range-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!