对if语句使用querydict项

时间:2017-04-22 15:02:43

标签: django django-templates

网址:myurl/?page=1&reverse

现在我想检查模板中是否有reverse

{% if request.GET.reverse %}
  do somthing
{% endif %}

ifendif之间的事情永远不会发生!

我应该使用什么而不是request.GET.reverse

1 个答案:

答案 0 :(得分:1)

为什么不将这个逻辑放在view内?像这样:

# Function Based View (FBV)

def my_view(request):
    reversed = request.GET.get('reverse', '')
    return render(request, 'template.html', locals())

# Class Based View (CBV)
class MyView(ListView):
    template_name = 'path/to/template.html'
    queryset = MyModel.objects.filter(...)
    context_object_name = 'my_obj'

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['reversed'] = self.request.GET.get('reverse', '')
        return context

然后做:

{% if reversed %}
    do somthing
{% endif %}

另一方面,如果您仍想在模板中执行此类逻辑,那么您应该像这样创建own filter

from django import template

register = template.Library()    

def is_in_dict(d, key):
    return key in d

并像这样使用它:

{% load my_filters %}

{% if request.GET|is_in_dict:"reverse" %}
    do somthing
{% endif %}