Django 模板迭代列表
我在 Django 视图中创建了一个列表:
list = [ elem1, elem2, ..., elemN ]
该列表是可变长度的:它可以包含 0-6 个元素。我想迭代模板中的列表,但我希望循环始终运行 6 次,为不存在的元素生成 None
或空字符串。
我尝试过这样的事情:
{% for i in "0123456" %}
{{ list.i }}
{% endfor %}
但这显然行不通。我知道我可以在视图中执行此操作,但我希望将其包含在模板中。有可能吗?
I have a list created in Django view:
list = [ elem1, elem2, ..., elemN ]
The list is variable length: it can contain 0-6 elements. I want to iterate over the list in the template, but I would like the loop to run always 6 times, yielding None
or empty string for non-existing elements.
I tried something like this:
{% for i in "0123456" %}
{{ list.i }}
{% endfor %}
but this obviously doesn't work. I know I could do this in the view, but I would like to have this in the template. Is is possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以添加一个 if 语句来检查是否是第六次循环。
http://docs.djangoproject.com/en/1.3/ref/文档中的 templates/builtins/#for 。
当然,如果您的列表很长,那么这并不是最佳选择。我还建议在views.py 中处理列表,然后将其传递给模板。如果可能的话,逻辑应该保留在视图中。
这使您可以控制完成的循环数量。要完全解决您的问题,您将需要一些额外的逻辑,但请参阅上面关于此的注释。
You can add an if statement checking if it is your 6th time through the loop.
http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#for in the docs.
Of course, if your list is very long then this is not optimal. I would also suggest processing the list in views.py and then passing it to the template. Logic should stay in the views if possible.
This gives you control over the number of loops done. To completely solve your problem you will need some addtional logic but see my note above regarding this.
检查此代码段:模板范围过滤器
Check this snippet: Template range filter