英文:
How to add active class in django?
问题
我有一个侧边栏,其中包含一些链接到某些页面的链接,如果URL与链接名称匹配,则具有活动类。但也有链接到我在模板中使用for循环添加的页面。我需要在打开它们时以某种方式添加活动类。我使用id
来链接它们。
template:
{% for branch in branches %}
<li>
<a href="{% url 'manager-branch-workers' branch.id %}">{{branch.name}}</a>
</li>
{% endfor %}
urls.py:
urlpatterns = [
...
path('workers/<int:pk>/', views.BranchWorkerList, name='manager-branch-workers')
]
我可以比较id和URL路径吗?
英文:
I have a sidebar where there are links to some pages that have active class if url matches to name of link. But there are also links to pages that I add with for loop in my template. I need to somehow add active class when they are opened. I use id
to link them.
template:
{% for branch in branches %}
<li>
<a href="{% url 'manager-branch-workers' branch.id %}">{{branch.name}}</a>
</li>
{% endfor %}
urls.py:
urlpatterns = [
...
path('workers/<int:pk>/', views.BranchWorkerList, name='manager-branch-workers')
]
Can I compare id and url path?
答案1
得分: 0
选项 1:
将 pk
的值作为模板上下文的一部分传递,并在模板中访问该值:
class BranchWorkerView(View):
def get(self, request, pk, *args, **kwargs):
...
context = {
"pk": pk,
}
return render(request, "template_name.html", context)
{% for branch in branches %}
<li>
<a
href="{% url 'manager-branch-workers' branch.id %}"
{% if pk == branch.id and request.resolver_match.url_name == "manager-branch-workers" %}
class="active"
{% endif %}>{{branch.name}}
</a>
</li>
{% endfor %}
选项 2:
直接从模板中的路径访问 pk
值:
{% for branch in branches %}
<li>
<a
href="{% url 'manager-branch-workers' branch.id %}"
{% if request.resolver_match.kwargs.pk == branch.id and request.resolver_match.url_name == "manager-branch-workers" %}
class="active"
{% endif %}>{{branch.name}}
</a>
</li>
{% endfor %}
在这两种情况下,你需要在模板中使用 resolver_match
属性来访问请求对象的一些数据。请参阅文档。
英文:
You've got two options available to you:
Option 1:
Pass the value of pk as part of your template context and access that value in the template:
class BranchWorkerView(View):
def get(self, request, pk, *args, **kwargs):
...
context = {
"pk": pk,
}
return render(request, "template_name.html", context)
{% for branch in branches %}
<li>
<a
href="{% url 'manager-branch-workers' branch.id %}"
{% if pk == branch.id and request.resolver_match.url_name == "manager-branch-workers" %}
class="active"
{% endif %}>
{{branch.name}}
</a>
</li>
{% endfor %}
Option 2:
Access the pk value directly from the path in your template:
{% for branch in branches %}
<li>
<a
href="{% url 'manager-branch-workers' branch.id %}"
{% if request.resolver_match.kwargs.pk == branch.id and request.resolver_match.url_name == "manager-branch-workers" %}
class="active"
{% endif %}>
{{branch.name}}
</a>
</li>
{% endfor %}
In both cases, you'll need to access some data from the request object by making use of the resolver_match
attribute within the template itself. See the documentation here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论