如何在Django模板中使用整数变量作为下标 [英] how to use integer variable as subscript in Django template

查看:74
本文介绍了如何在Django模板中使用整数变量作为下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django模板中有一个for循环:

I have a for loop in a Django template:

{% for i in no_of_lift_series_range %}
    {{ workout.lifts.series.i.activity_name }}
{% endfor %}

此处无法输出任何内容.问题在于使用 i .我知道这一点,因为:

where this fails to output anything. The problem lies in the use of i. I know this, because this:

{% for i in no_of_lift_series_range %}
    {{ workout.lifts.series.0.activity_name }}
{% endfor %}

输出应该输出的内容.为什么我不能以我想要的方式使用 i 以及如何使它起作用?

outputs what it is supposed to output. Why can't I use i in the way I want and how do I make this work?

推荐答案

我将创建

I would create custom template filter to get the list item by index:

@register.filter
def get_by_index(mylist, index):
    return mylist[index]

您可以这样使用它:

{% for i in no_of_lift_series_range %}
    {% with item=workout.lifts.series|get_by_index:i %}
        {{ item.activity_name }}
    {% endwith %}
{% endfor %}

这篇关于如何在Django模板中使用整数变量作为下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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