0

我正在编写一个建立在 django 框架背后的 python 网站,我正在寻找一种方法来突出显示用户依赖于 URL 的当前链接,我认为做这样的事情会起作用。

我所做的是创建一个名为nav并构建了一些模板标签的新应用程序,就像这样,

from django import template

register = template.Library()

URL_PATTERNS = {
    'home': (r'^/$',),
}

@register.tag
def nav_selection(parser, token):
    try:
        tag_name, nav_item = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    if not (nav_item[0] == nav_item[-1] and nav_item[0] in ('"', "'")):
        raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
    return NavSelectionNode(nav_item[1:-1])

class NavSelectionNode(template.Node):
    def __init__(self, nav_item):
        self.nav_item = nav_item
    def render(self, context):
        if not 'request' in context:
          return "" 
        import re
        try:
            regs = URL_PATTERNS[self.nav_item]
        except KeyError:
            return ''
        for reg in regs:
            if re.match(reg, context['request'].get_full_path()):
                return "active"
        return ''

在我的模板中,我这样做

<ul id="navigation">{% load nav %}
                <li><a href="{% url views.home %}" class='{% nav_selection "home" %}'>home</a></li>
                <li><a href="{% url views.about %}" class='{% nav_selection "about" %}'>about neal &amp; wolf</a></li>
                <li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>our products</a></li>
                <li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>shop</a></li>
                <li><a href="{% url views.look %}" class='{% nav_selection "look" %}'>get the look</a></li>
                <li><a href="{% url news.views.index %}" class='{% nav_selection "news" %}'>news</a></li>
                <li><a href="{% url contact.views.contact %}" class='{% nav_selection "contact" %}'>contact us</a></li>
                <li><a href="{% url store_locator.views.index %}" class='{% nav_selection "finder" %}'>salon finder</a></li>
                <li><a href="{% url professional.views.index %}" class='{% nav_selection "contact" %}'>neal &amp; wolf professional</a></li>

            </ul>

然而我在萤火虫中得到的标记是这个例子中我正在浏览索引页面

<a class="" href="/home/">

所以显然有些事情失败了,但我看不到哪里,有人可以帮我吗?

4

1 回答 1

0

需要检查的一些事项:

request对象实际上是否在您的上下文中?您是专门传递它,还是使用RequestContext?

为什么要在模板标签中定义正则表达式,而不是使用内置reverse函数在 urlconf 中查找它们?

这里的正则表达式实际上与 urlconf 中的正则表达式匹配吗?

您是否home以某种方式将您的 urlconf 包含在“home”网址下?

于 2009-12-11T14:52:50.873 回答