首页 > 解决方案 > 在Django中根据if条件选择for循环

问题描述

在 Django 中,如何编写条件以选择两个for循环之一?

{% if type == 'type_one' %}
{% for object in type_one_ojects %}
{% elif type == 'type_two' %} # this_line
{% for object in type_two_ojects %}
...
########## Given error ##########
# Invalid block tag on this_line: 'elif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?

标签: pythondjango

解决方案


这样的逻辑不属于模板,而是属于视图。实际上,模板关注的是呈现逻辑,而不是业务逻辑。在视图中,您可以检查类型是否为type_oneortype_two并相应地传递项目集。

因此,视图应如下所示:

def some_view(request):
    # …
    objects = type_one_objects if type == 'type_one' else type_two_objects
    context = { 'objects': objects }
    return render(request, '%name_of_template.html', context)

然后在模板中枚举:

{% for object in objects %}
    <!-- … -->
{% endfor %}

推荐阅读