Navigation in django

后端 未结 30 1389

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

    I liked the cleanness of 110j above so I took most of it and refactored to solve the 3 problems I had with it:

    1. the regular expression was matching the 'home' url against all others
    2. I needed multiple URLs mapped to one navigation tab, so I needed a more complex tag that takes variable amount of parameters
    3. fixed some url problems

    Here it is:

    tags.py:

    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, patterns):
            self.patterns = patterns
        def render(self, context):
            path = context['request'].path
            for p in self.patterns:
                pValue = template.Variable(p).resolve(context)
                if path == pValue:
                    return "active" # change this if needed for other bootstrap version (compatible with 3.2)
            return ""
    

    urls.py:

    urlpatterns += patterns('',
        url(r'/$', view_home_method, {}, name='home_url_name'),
        url(r'/services/$', view_services_method, {}, name='services_url_name'),
        url(r'/contact/$', view_contact_method, {}, name='contact_url_name'),
        url(r'/contact/$', view_contact2_method, {}, name='contact2_url_name'),
    )
    

    base.html:

    {% load tags %}
    
    {% url home_url_name as home %}
    {% url services_url_name as services %}
    {% url contact_url_name as contact %}
    {% url contact2_url_name as contact2 %}
    
    
    

提交回复
热议问题