Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

python - Django dynamically get view url and check if its the current page

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...