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.
JavaScript
x
2
1
<a class="list-group-item {% if '?q=' in request.path %}active{% endif %}" href="{% url 'blah'%}"> Foo </a>
2
Thank you in advance.
Advertisement
Answer
Get it in view
and send it as parameter in render
JavaScript
1
4
1
active = ('?q=' in request.path)
2
3
render( , context={"active": active})
4
and use it in template
JavaScript
1
2
1
class="list-group-item {% if active %}active{% endif %}"
2
Or get it as
JavaScript
1
7
1
if '?q=' in request.path:
2
extra_class = "active"
3
else:
4
extra_class = ""
5
6
render( , context={"extra_class": extra_class})
7
and set in template without if
JavaScript
1
2
1
class="list-group-item {{ extra_class }}"
2
BTW:
You could get it also as
JavaScript
1
4
1
query = request.GET.get('q', '')
2
3
render( , context={"query": query})
4
and use it in template to set class and to display query
JavaScript
1
4
1
You search: {{ query }}
2
3
class="list-group-item {% if query %}active{% endif %}"
4