Django:根据当前的request.path在模板中创建变量(不使用{%with%})

2024-04-27 19:55:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图将分页添加到我的第一个Django项目中,但我正努力想解决一些问题

假设我在上下文中作为字典传递

bugs = {
    'critical': <QUERY TO BRING BACK CRITICAL>,
    ...
    'all': <QUERY TO BRING BACK ALL>
}

context = {
    'bugs': bugs,
}

然后在我的模板中:

{% if request.path == '/bugs/critical' %}
    {% if bugs.critical.paginator.count >= 5 %}
        {% if bugs.critical.has_previous %}
            do something
        {% endif %}
    {% endif %}
{% elif request.path == '/bugs/all' %}
    {% if bugs.all.paginator.count >= 5 %}
        {% if bugs.all.has_previous %}
            do something
        {% endif %}
    {% endif %}
{% endif %}

我有类似的东西,但不仅仅是critical和all,我想知道如何压缩我的代码,这样我只有一个分页需要更新,bugs.allbugs.critical就像一个模板变量,取决于路径?我试着这样做:

{% if request.path == '/bugs/critical' %}
    {% with key='critical' %}{% endwith %}
{% endif %}

但是它似乎使用with来设置变量,必须在with块中完成,这意味着我仍然需要使用相同的代码,比如5次

有什么想法吗


Tags: topath模板ifrequestcountwithback