Navigation in django

后端 未结 30 1434

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

    I took the code from nivhab above and removed some wierdness and made it into a clean templatetag, modified it so that /account/edit/ will still make /account/ tab active.

    #current_nav.py
    from django import template
    
    register = template.Library()
    
    @register.tag
    def current_nav(parser, token):
        import re
        args = token.split_contents()
        template_tag = args[0]
        if len(args) < 2:
            raise template.TemplateSyntaxError, "%r tag requires at least one argument" % template_tag
        return NavSelectedNode(args[1])
    
    class NavSelectedNode(template.Node):
        def __init__(self, url):
            self.url = url
    
        def render(self, context):
            path = context['request'].path
            pValue = template.Variable(self.url).resolve(context)
            if (pValue == '/' or pValue == '') and not (path  == '/' or path == ''):
                return ""
            if path.startswith(pValue):
                return ' class="current"'
            return ""
    
    
    
    #template.html
    {% block nav %}
    {% load current_nav %}
    {% url home as home_url %}
    {% url signup as signup_url %}
    {% url auth_login as auth_login_url %}
    
    {% endblock %}
    

提交回复
热议问题