Navigation in django

后端 未结 30 1390

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

    I just wanted to share my minor enhancement to nivhab's post. In my application I have subnavigations and I did not want to hide them using just CSS, so I needed some sort of "if" tag to display the subnavigation for an item or not.

    from django import template
    register = template.Library()
    
    @register.tag
    def ifnaviactive(parser, token):
        nodelist = parser.parse(('endifnaviactive',))
        parser.delete_first_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:], nodelist)
    
    class NavSelectedNode(template.Node):
        def __init__(self, patterns, nodelist):
            self.patterns = patterns
            self.nodelist = nodelist
    
        def render(self, context):
            path = context['request'].path
            for p in self.patterns:
                pValue = template.Variable(p).resolve(context)
                if path == pValue:
                    return self.nodelist.render(context)
            return ""
    

    You can use this basically in the same way as the active tag:

    {% url product_url as product %}
    
    {% ifnaviactive request product %}
        
    {% endifnaviactive %}
    

提交回复
热议问题