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>

それでも、firebug で取得するマークアップはこれです。この例では、インデックス ページを閲覧しています。

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

明らかに何かが失敗していますが、どこにあるのかわかりません。誰か助けてください。

4

1 に答える 1

0

確認事項:

オブジェクトはrequest実際にあなたのコンテキストにありますか? 具体的に渡していますか、それとも ? を使用していRequestContextますか?

reverse組み込み関数を使用して urlconf で検索するのではなく、テンプレートタグで正規表現を定義するのはなぜですか?

ここの正規表現は実際に urlconf のものと一致しますか?

homeどういうわけか「ホーム」URLの下にurlconfを含めましたか?

于 2009-12-11T14:52:50.873 に答える