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

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

问题描述

考虑这个基本菜单:

  

我正在尝试给当前页面的链接一个活动类,我想做动态基于当前网址和视图的网址。所以当用户访问关于页面时,该页面现在有活动类,主页没有。



我想在< li>< / li> 标签:

  {%if request.get_full_path ={%url'home'%}%} class =active {%endif%} 
{%if request.get_full_path ={%url'about'%}%} class =active{%endif%}
/ pre>

但显然我不能将两个 {%...%} 嵌套在彼此之间。 / p>

任何关于如何解决这两个问题的想法?

解决方案

我通常在我的导航中使用模板继承,类似于回复与...相关联的alecxe 。但是,可以比较使用if标签中的当前URL,正如您所尝试的那样。



url 标签可以保存结果到一个变量。然后,您可以在if标签中使用该变量。

  {%url'home'a​​s home_url%} 
{ %if request.get_full_path == home_url%} class =active{%endif%}


Consider this basic menu:

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

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.

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?

解决方案

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.

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 %}
{% if request.get_full_path == home_url %}class="active"{% endif %}

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

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