<!-- base.html -->
{% block navigation %}
<nav>
{% for menu_item in menu_items %}
<a href="{{ menu_item.url }}" class="{% if request.path == menu_item.url %}active{% endif %}">
{{ menu_item.label }}
</a>
{% endfor %}
</nav>
{% endblock %}
# views.py
def home_view(request):
context = {'menu_items': Menu.objects.all()}
return render(request, 'base.html', context)Scenario: Hari's Dynamic Navigation Menu Problem
request.path is not available in templates; use request.get_full_path() instead.
The request object is automatically available in templates, and request.path contains the current URL path.
To access the request in templates, it must be explicitly passed in the context dictionary.
Comparing request.path with menu URLs requires URL name resolution using {% url %} tag.
Show answer & explanationAnswer
Correct answer
The request object is automatically available in templates, and request.path contains the current URL path.
Explanation
The template accesses the current request path using {{ request.path }} to highlight the active menu item. The request object is automatically available in templates when using Django's render function. The {% if %} condition compares paths to apply the 'active' class dynamically.
All 29 Django Templates and Template Tags questions
- 1.What is the primary purpose of Django Templates?
- 2.Which template tag is used to iterate over a list in Django templates?
- 3.What is the correct syntax to display a variable in a Django template?
- 4.Which template tag is used to include conditional logic in Django templates?
- 5.What does the Django template filter 'upper' do?
- 6.How do you apply a filter to a variable in a Django template?
- 7.What is the purpose of the {% extends %} template tag?
- 8.Which template tag is used to define a block that can be overridden in child templates?
- 9.What does the 'length' filter return in Django templates?
- 10.How do you access dictionary values in a Django template?
- 11.Understanding Django Template Inheritance and Block Tags
- 12.Django Custom Template Filters - Implementation and Usage
- 13.Django Template Tag for Conditional Rendering - if/elif/else
- 14.Scenario:
- 15.Django Template For Loop with Filtering and Counters
- 16.Scenario:
- 17.Django Template Tags - Static Files Loading
- 18.Django Template Tags - CSRF Protection in Forms
- 19.Scenario:
- 20.Understanding Django Template Inheritance and Block Tags
- 21.Debugging Template Variable Output
- 22.Scenario:
- 23.Custom Template Filter Implementation
- 24.Template Tag with Arguments - Practical Implementation
- 25.Scenario:
- 26.Conditional Logic and Template Tags
- 27.Built-in Template Filters for Data Formatting
- 28.For Loop and Loop Variable in Templates
- 29.Scenario:
