我想在另一个for循环中使用一个循环中的值。但是我在views.py的上下文字典中的表变量中有3个值。我想通过for循环提取这些值,并通过另一个for循环返回它们,但是第二个for循环将第一个for循环的值视为字符串。
{% for table in tables %}
{% for music in table %}
<a class="{{ table }}" href="javascript:void(0);" onclick="playSong('{{ music }}')">{{ music }}</a>
{% endfor %}
{% endfor %}
页面内来源:
<a class="Rap" href="javascript:void(0);" onclick="playSong('R')">R</a>
<a class="Rap" href="javascript:void(0);" onclick="playSong('a')">a</a>
<a class="Rap" href="javascript:void(0);" onclick="playSong('p')">p</a>
我想要说唱表中的值,而不是a标签中的R,a,p之类的输出。 2. for循环将其视为一个字符串,但是在我的上下文字典中有Rap关键字及其值。我想绘制此关键字的值。
答案 0 :(得分:0)
编辑: 根据{{3}}或this answer,您无法使用“裸” Django模板语言中的动态键(即for循环中的变量)访问字典中的项目。您必须像这样创建this other answer:
from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
有关更多信息,请参见链接的答案。
如果您的tables
是字典,则对其进行迭代实际上是对键而不是整个键/值对进行迭代。我想这就是你想要的:
{% for music, songs in tables.items %}
{% for song in songs %}
<a class="{{music}}" href="javascript:void(0);" onclick="playSong('{{song}}')">{{song}}</a>
{% endfor %}
{% endfor %}