最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Styling current navigation menu item in Django - Stack Overflow

programmeradmin1浏览0评论

I would like to style currently active submenu item in Django. I am wondering how should I do it? I can think of 2 ways:

  • Django Side: where I compare current address with link and then I add inside Django template
  • jQuery side: where Django template knows nothing about active menu item nad I do highlights using jQuery

I am more prone to do it jQuery way, but is my way of thinking good? Is this solution not recommended somehow?

I would like to style currently active submenu item in Django. I am wondering how should I do it? I can think of 2 ways:

  • Django Side: where I compare current address with link and then I add inside Django template
  • jQuery side: where Django template knows nothing about active menu item nad I do highlights using jQuery

I am more prone to do it jQuery way, but is my way of thinking good? Is this solution not recommended somehow?

Share Improve this question asked Apr 7, 2015 at 8:21 connexion20000connexion20000 3353 silver badges16 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 21

@Liarez in his answer wrote:

In this example I make difference for 3 urls, this can be messy if you have an URL that is like /posts/whatever/contacts because there is 2 places that will return True (2nd and 3rd li)

So here is the better option for handling this:

{% with request.resolver_match.url_name as url_name %}
    <ul id="menu">
        <li class="{% if url_name == 'home' %}active{% endif %}">Home</li>
        <li class="{% if url_name == 'blog' %}active{% endif %}">Posts</li>
        <li class="{% if url_name == 'contact' %}active{% endif %}">Contact</li>
    </ul>
{% endwith %}

Now we don't have problem with duplications in our url paths. That will work, assuming that you have wrote your url patterns with names like this:

url(r'^$', 'home_view', name=u'home'),
url(r'^posts/$', 'posts_view', name=u'blog'),
url(r'^contact/$', 'contact_view', name=u'contact'),

To show active tabs in menus & submenus I use request.path in the Templates and one class called active.

When you do

{{request.path}}

in a template it returns the url where you are(something like /posts/1234). So in your HTML you can do something like:

<ul id="menu">
    <li class="{% if request.path == '/' %}active{% endif %}">Home</li>
    <li class="{% if 'posts' in request.path %}active{% endif %}">Posts</li>
    <li class="{% if 'contact' in request.path %}active{% endif %}">Contact</li>
</ul>

In this example I make difference for 3 urls, this can be messy if you have an URL that is like /posts/whatever/contacts because there is 2 places that will return True (2nd and 3rd li)

But If you have very different urls this could be one of the easiest ways to do what you're trying to do

发布评论

评论列表(0)

  1. 暂无评论