Navigation in django

后端 未结 30 1404

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

    Just another ehnancement of the original solution.

    This accept multiple patterns and which is best also unnamed patterns written as relative URL wrapped in '"', like following:

    {% url admin:clients_client_changelist as clients %}
    {% url admin:clients_town_changelist as towns %}
    {% url admin:clients_district_changelist as districts %}
    
    
  • Home
  • Clients
  • {% if request.user.is_superuser %}
  • Settings
  • {% endif %}

    Tag goes like this:

    from django import template
    
    register = template.Library()
    
    @register.tag
    def active(parser, token):
        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, urls):
            self.urls = urls
    
        def render(self, context):
            path = context['request'].path
    
            for url in self.urls:
                if '"' not in url:
                    cpath = template.Variable(url).resolve(context)
                else:
                    cpath = url.strip('"')
    
                if (cpath == '/' or cpath == '') and not (path == '/' or path == ''):
                    return ""
                if path.startswith(cpath):
                    return 'active'
            return ""
    

提交回复
热议问题