Navigation in django

后端 未结 30 1481

I\'ve just done my first little webapp in django and I love it. I\'m about to start on converting an old production PHP site into django and as part its template, there is a

30条回答
  •  孤独总比滥情好
    2020-11-27 09:38

    My solution was to write a simple context processor to set a variable based on the request path:

    def navigation(request):
    """
    Custom context processor to set the navigation menu pointer.
    """
    nav_pointer = ''
    if request.path == '/':
        nav_pointer = 'main'
    elif request.path.startswith('/services/'):
        nav_pointer = 'services'
    elif request.path.startswith('/other_stuff/'):
        nav_pointer = 'other_stuff'
    return {'nav_pointer': nav_pointer}
    

    (Don't forget to add your custom processor to TEMPLATE_CONTEXT_PROCESSORS in settings.py.)

    Then in the base template I use an ifequal tag per link to determine whether to append the "active" class. Granted this approach is strictly limited to the flexibility of your path structure, but it works for my relatively modest deployment.

提交回复
热议问题