Navigation in django

后端 未结 30 1433

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:57

    I found the best is to use an inclusion tag:

    templates/fnf/nav_item.html

    
    

    This is just my basic bootstrap nav item I wish to render.

    It gets the href value, and optionally the link_name value. is_active is calculated based on the current request.

    templatetags/nav.py

    from django import template
    
    register = template.Library()
    
    
    @register.inclusion_tag('fnf/nav_item.html', takes_context=True)
    def nav_item(context, url_name, link_name=None):
        return {
            'url_name': url_name,
            'link_name': link_name or url_name.title(),
            'is_active': context.request.resolver_match.url_name == url_name,
        }
    

    Then use it in a nav: templates/fnf/nav.html

    {% load nav %}
    

提交回复
热议问题