How to add class="active"
into HTML tag according to the URL of current page:
Settings
Because we need to access request context in template, so add the following settings if you haven’t.
1 | TEMPLATE_CONTEXT_PROCESSORS = ( |
Template Tags
Create templatetags
directory with common_tags.py
under APP_NAME
:
I only use simple string matching (
if stringA in stringB: ...
). Feel free to modify if you want to use RegExp.
1 | # APP_NAME/templatetags/common_tags.py |
Using in Template
First, add:
1 | {% load common_tags %} |
at the top of your template file.
Read the code and you will know what they mean and the differences among the three tags:
By URL
1 | <a href="{{ child.get_absolute_url }}" class="{% is_active request child.get_absolute_url %}"> |
By URL Name & reverse()
1 | <li class="{% is_active_reverse request 'show_current_user_profile' %}"> |
But in many condition, reverse()
is very hard/inconvenient to use if the URL pattern needs pk
or other kwargs. So we use another more universal way, resolve()
:
By URL Name & resolve()
1 | <a class="{% is_active_resolve request 'all_products' 'products_under_category' %}" |
resolve()
needs only URL name, without pk
or so.
Notice the three tags can accept multiple arguments (
all_products
,products_under_category
).