有没有办法在模板中使用标志变量?

时间:2014-06-01 19:17:49

标签: django django-templates

我循环遍历结果集,当满足某个条件时,我想运行条件语句。在满足该条件之后,我希望继续循环遍历结果集而不运行该条件。

有没有人对如何解决这个问题有任何想法?

编辑:

这是我想要实现的目标。

{% flag = false %}
{% for row in results %}
    {{ row.field }}
    {% if row.is_active and !flag %}
        <br />
        {% flag = true %}
    {% endif %}
{% endfor %}

2 个答案:

答案 0 :(得分:0)

看起来你想用QuerySet的第一部分做一件事,剩下的就是其他事情。在视图中拆分它。

<强> views.py

def split_list(list, condition):
    list1, list2 = [], []
    condition_satisfied = False
    for element in list:
        if not condition_satisfied and condition(element):
            condition_satisfied = True
        if not condition_satisfied:
            list1.append(element)
        else:
            list2.append(element)
    return list1, list2

def your_view(request):
    results = YourModel.objects.all()
    results1, results2 = split_list(results, condition)
    return render(request, 'template.html', {
        'results1': results1,
        'results2': results2
    })

<强> template.html

{% for result in results1 %}
    {% if result == whatever %}
        <p>Condition satisfied</p>
    {% else %}
        <p>Condition not satisfied</p>
    {% endif %}
{% endfor %}
{% for result in results2 %}
    {{ result }}
{% endfor %}

答案 1 :(得分:0)

Django没有这个功能,并且有充分的理由。模板不应包含这种逻辑。它应该在View中完成。