python - 访问模板中的视图变量
问题描述
我有一个动态的上下文变量,因为我执行了一个循环:
context['categories'] = choices.CATEGORIES
for category_type, category in context['categories']:
context[category_type] = Article.objects.filter(category=category_type).count()
但在模板中,它只打印类别类型而不是变量上的数字,但我还需要链接类型:
{% for type, category in categories %}
<a href="{% url 'app:category' type %}">{{category}}</a>
{{type}}
{% endfor %}
如何在 for 循环中访问此动态变量?
解决方案
您应该使用items
for 循环中的方法,例如:
{% for type, category in categories.items %}
<a href="{% url 'app:category' type %}">{{ category }}</a>
{% endfor %}
推荐阅读
- python - 哪个查询使用 OSMnx 重现城市街道网络方向图?
- amazon-web-services - 在使用之前查看 AWS SQS 队列消息
- c# - 迭代器模式,如何使其通用?
- asp.net-mvc - 更改 DateFormat 未按预期工作
- javascript - 如何在给定的时间间隔内自动刷新网页所有控件
- r - 如何使用数据框值自定义 R Shiny 中的日期选择
- android - 底部导航视图。使用深度链接导航到目的地导致也在第一个选项卡中添加目的地片段
- sql - String to datetime conversion in sql server
- python - Django:无法在模型中保存值
- c# - 如何从 DllImport 获取字符串数组