Search code examples
pythondjangogetparameter

Django How to get GET parameters in template



I'm working on a django project.
I'm wondering how to get GET parameters in template so that I can make corresponding tab active.
I tried the code below, but it didn't work.
<a class="list-group-item {% if '?q=' in request.path %}active{% endif %}" href="{% url 'blah'%}"> Foo </a>

Thank you in advance.


Solution

  • Get it in view and send it as parameter in render

    active = ('?q=' in request.path)
    
    render(..., context={"active": active}) 
    

    and use it in template

    class="list-group-item {% if active %}active{% endif %}"
    

    Or get it as

    if '?q=' in request.path:
       extra_class = "active"
    else:
       extra_class = ""
    
    render(..., context={"extra_class": extra_class})
    

    and set in template without if

    class="list-group-item {{ extra_class }}"
    

    BTW:

    You could get it also as

    query = request.GET.get('q', '')
    
    render(..., context={"query": query})
    

    and use it in template to set class and to display query

    You search: {{ query }}
    
    class="list-group-item {% if query %}active{% endif %}"