首页 > 解决方案 > 访问模板中的视图变量

问题描述

我有一个动态的上下文变量,因为我执行了一个循环:

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 循环中访问此动态变量?

标签: pythondjango

解决方案


您应该使用itemsfor 循环中的方法,例如:

{% for type, category in categories.items %}
    <a href="{% url 'app:category' type %}">{{ category }}</a>
{% endfor %}

推荐阅读