search

Home  >  Q&A  >  body text

python - About looping lists in django templates

There is a navigation bar, and I want to add a class = 'on' attribute when this navigation is activated
If you click on the second navigation item, add this class to the second item

{% for nav in NAV %}
<li>nav</li>
{% end for %}

for example

<li class="on">第一项</li>
<li>第二项</li>
<li>第三项</li>

How to implement this?

欧阳克欧阳克2700 days ago968

reply all(2)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-07-05 10:36:48

    #后端
    navs = [
        {'name': '菜单1', 'url': 'url1'},
        {'name': '菜单2', 'url': 'url2'}
    ]
    
    for nav in navs:
        nav['class'] = 'on' if nav['url'] == request.path else None
        
    #前端
    {% for nav in navs %}
    <li class={{ nva.class }}>{{ nva.name }}</li>
    {% end for %}

    reply
    0
  • ringa_lee

    ringa_lee2017-07-05 10:36:48

    You have nothing to do with django.
    This is a problem with the front-end page. For example:
    You load all the navigation to the front-end page at once, and then you need to open the current menu based on clicks, and then turn off the effects of other menus, right?
    If I understand correctly, this is a front-end problem

    1. Bootstrap or UIKit all support this effect;

    2. Write the navigation style yourself, for example, name it active, and then give you the clicked object in jQuery $(this).addClass('active'), this is an idea;

    reply
    0
  • Cancelreply