我想要得到以下工作。用于循环变量作为Django模板中的字典键
计数循环需要遍历所有值,并且可能没有与每个计数相关联的用户,但需要在每个循环中使用计数值i
传递给JavaScript。
蟒蛇部分:
users = {}
users[1]={}
users[1][id]=...
users[1][email]=...
...
count=[1,2,3,4,5,6,7,8,9,10]
Django的模板部分:
{% for i in count %}
do some stuff with the value i using {{i}} which always returns the value, i.e. 1
email:{% if users.i.email %}'{{users.i.email}}'{% else %}null{% endif%}
{% endfor %}
这不返回任何电子邮件。 当我替补人数1
为i
在{% if user.i.email %}
电子邮件返回用户的电子邮件地址。 我在JavaScript中使用数据,因此如果它不存在,它需要隐式为空。 我似乎无法让Django将i
变量识别为变量而不是值i。
使用[]
不起作用,因为它抛出一个无效的语法错误
email:{% if users.[i].email %}'{{users.[i].email}}'{% else %}null{% endif%}
我一直在使用 “with
” 语句
{% for i in count %}{% with current_user=users.i %}...
,然后使用current_user.email
尝试,但不会返回任何
也试图
{% for i in count %}{% with j=i.value %}...
以防万一它会工作,然后试图用j
,但同样的结果。
我曾想过建立一个内部for循环遍历用户对象和检查,如果我是等于键/值,但似乎昂贵,不是很可扩展性。
任何想法我怎么能强迫Django的查看i
作为一个变量和使用它的值作为索引,或任何其他方式解决这个问题?
感谢
Jayd
* 编辑:
我尝试了额外的循环,通过ABHI的建议,以下。
{% for i in count %}
{% for key, current_user in users.items %}
do some stuff with the value i using {{i}} which always returns the value, i.e. 1
email:{% if i == key and current_user.email %}'{{current_user.email}}'{% else %}null{% endif%}
{% endfor %}
{% endfor %}
这种类型的作品,但现在它会重复do some stuff with the value i
为用户的每一个值。如果我把一个if:
{% for i in count %}
{% for key, current_user in users.items %}
{% if i == key %}
do some stuff with the value i using {{i}} which always returns the value, i.e. 1
email:{% if i == key and current_user.email %}'{{current_user.email}}'{% else %}null{% endif%}
{% endif%}
{% endfor %}
{% endfor %}
当计数没有一个特定的用户时,忽略循环。
我可以解决此看到的唯一方法是有那个我想用current_user
每个地方的用户环路。
{% for i in count %}
do some stuff with the value i using {{i}} which always returns the value, i.e. 1
email:{% for key, current_user in users.items %}{% if i == key and current_user.email %}'{{current_user.email}}'{% else %}null{% endif%}{% endfor %}
{% endfor %}
而这看起来非常昂贵。 任何想法?
我在想,也许的写一个过滤器,使用i
作为关键用户返回值:
{% with current_user=users|getuser:i %}
但我不知道这是否会工作或我会得到同样的错误,在这里i
作为值“i”而不是变量名传递。
我会试一试这么久。
* 编辑
这没有奏效。 过滤器使用{{}}
返回对象,但它不在{% %}
内工作。
感谢输入
你为什么要使用字典外集合,而不是一个列表? –
为什么在整个问题中使用** bold **格式,而不是在编辑框右侧显示明确的格式提示? –
格式化的道歉,我没有看到我发布帖子时的提示。 – Jayd