Django 动态获取视图 url 并检查其是否为当前页面 [英] Django dynamically get view url and check if its the current page

查看:28
本文介绍了Django 动态获取视图 url 并检查其是否为当前页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个基本菜单:

<ul class="nav navbar-nav">
  <li class="active"><a href="{% url 'home' %}">Home</a></li>
  <li><a href="{% url 'about' %}">About</a></li>
</ul>

我正在尝试为当前页面的链接提供一个活动类,并且我想根据当前 url 和视图的 url 动态执行此操作.这样当用户访问关于页面时,该页面现在具有活动类,而主页则没有.

I'm trying to give the current page's link an active class, and I want to do this dynamically based on current url and the view's url. So that when a user visits the about page, that page now has the active class and the homepage does not.

我想在 <li></li> 标签内按照这样的逻辑工作:

I'd like to logic to work like this inside of the <li></li> tags:

{% if request.get_full_path = "{% url 'home' %}" %}class="active"{% endif %}
{% if request.get_full_path = "{% url 'about' %}" %}class="active"{% endif %}

但显然我不能有两个 {% ... %} 嵌套在彼此内部.

but clearly I cant have two {% ... %} nested inside of each other.

关于如何避免嵌套两者的任何想法?

Any ideas on how to get around nesting the two?

推荐答案

我通常在导航中使用模板继承,类似于 回答 alecxe 链接到.但是,可以在 if 标记中比较使用当前 URL,就像您尝试做的那样.

I usually use template inheritance in my navigation, in a similar way to the answer alecxe linked to. However, it is possible to compare the use the current URL in an if tag, as you are trying to do.

url 标签允许您将结果保存到变量中.然后,您可以在 if 标签中使用该变量.

The url tag allows you to save the result to a variable. You can then use that variable in your if tag.

{% url 'home' as home_url %}
<a href="{{ home_url }}" {% if request.get_full_path == home_url %}class="active"{% endif %}>Home</a>

这篇关于Django 动态获取视图 url 并检查其是否为当前页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆