Jinja / Django的循环范围不起作用 [英] Jinja / Django for loop range not working

查看:139
本文介绍了Jinja / Django的循环范围不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Django模板,用于根据从视图传递的参数复制图像;模板然后在for循环中使用Jinja2复制图像。

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.

但是,我只能通过在视图中传递一个列表来使其工作。如果尝试使用jinja范围,则会收到错误消息(无法解析余数:...)。

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.

模板

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

我检查了要传递的变量;它是int类型。哎呀,我什至试图摆脱变量(用于测试)并尝试使用硬编码数字:

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

我收到以下错误:


无法解析其余部分:'(5)'from'range(5)'

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

如果我将参数字典中的一个列表传递给模板(并使用该列表代替range语句),它将起作用;

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.

我缺少什么? Jinja上的文档( for循环范围)和上一个链接都告诉我这应该适用于范围和变量。

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.

推荐答案

Soooo ....基于Franndy的评论,Django不会自动支持此评论,并遵循他们的链接,该链接指向此链接,我找到了如何编写自己的过滤器。

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.

views.py 内部:

from django.template.defaulttags import register

@register.filter
def get_range(value):
    return range(value)

然后,在模板

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

这篇关于Jinja / Django的循环范围不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆