2009-12-11 42 views
0

我正在寫一個python網站建立在django框架的背面,我正在尋找一種方法來突出顯示當前鏈接用戶正在取決於什麼URL,我認爲做一些這樣的事情會起作用。給積極的類到活動鏈接

我所做的是創建一個名爲nav新的應用程序,並建立了一些templatetags,像這樣,

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/"> 

所以有些東西顯然是失敗的,但我看不到在哪裏,有誰能幫助我嗎?

回答

0

有些事情要檢查:

是在request對象實際上在你的背景?你是專門傳遞它,還是使用RequestContext

爲什麼要在模板標籤中定義正則表達式,而不是使用內置reverse函數在urlconf中查找它們?

這裏的正則表達式是否與urlconf中的正則表達式匹配?

你有沒有在'home'網址下包含你的home urlconf?

+0

對不起,當談到python時,我真的很厚,只做了大約2周,這是正確的方法嗎?這不是我的代碼,我繼承了它,有沒有更簡單的方法?我如何查看請求對象中的內容?當我render_to_response時,我的最後一個參數是RequestContext,那是什麼意思?對不起,我很愚蠢。 – Udders 2009-12-11 15:34:18