0

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.

Ajay saini
  • 2,352
  • 1
  • 11
  • 25
  • get it in `view` and send it as parameter in `render(..., context={"active":True})` and use it `{% if active %}active{% endif %}` or set it as `context={"extra_class": "active"}` or `context={"extra_class": ""}` and set without `if` as `"list-group-item {{ extra_class }}"` – furas Jul 12 '21 at 02:43
  • @furas Could you have a look at this question as well?https://stackoverflow.com/questions/68341820/how-to-align-decimal-point-of-price-in-django-template –  Jul 12 '21 at 04:15
  • @furas Could you post it as an answer? –  Jul 12 '21 at 05:26

1 Answers1

0

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 %}"
furas
  • 134,197
  • 12
  • 106
  • 148