Navigation in django

后端 未结 30 1393

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

    Slightly modifying Andreas' answer, it looks like you can pass in the name of the route from urls.py to the template tag. In my example my_tasks, and then in the template tag function use the reverse function to work out what the URL should be, then you can match that against the URL in the request object (available in the template context)

    from django import template
    from django.core.urlresolvers import reverse
    
    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, name):
            self.name = name
    
        def render(self, context):
    
            if context['request'].path == reverse(self.name[1]):
                return 'active'
            else:
                return ''
    

    urls.py

    url(r'^tasks/my', my_tasks, name = 'my_tasks' ),
    

    template.html

  • Everyone
提交回复
热议问题