2016-07-25 70 views
0

我想根據我的活動URL來隱藏/顯示我的導航部分。Django根據URL顯示列表項目

我試圖用re.match()方法做這個,但是忍者不喜歡這個。此代碼位於我的側面導航的HTML包含文件中,如下所示:

<ul> 
{% if bool(re.match('^/url/path', request.get_full_path)) %} 
    <li><a href='link1'>Link1</a></li> 
    <li><a href='link1'>Link2</a></li> 
    <li><a href='link1'>Link3</a></li> 
{% endif %} 
</ul> 

在此先感謝。

回答

1

您可以創建custom filter並使用它。可能是這樣的;

# nav_active.py 
import re 
from django.template import Library 
from django.core.urlresolvers import reverse 

register = Library() 

@register.filter() 
def nav_active(request_path, search_path): 
    # WRITE YOUR LOGIC 
    return search_path in request_path 

在模板中

{% load nav_active %} 
{% if request_path|nav_active:"/search/path" %} 
.... 
{% endif %} 

更新,按您的評論。從Django的docs code layout section自定義模板標籤和過濾器:

The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the init.py file to ensure the directory is treated as a Python package.

因此,創建在同一級別的文件夾爲您view.py並將其命名爲templatetags。 (不要忘記在裏面添加__init__.py)。在與__init__.py相同的級別添加您的nav_active.py,並且應該可以使用。像這樣:

yourapp/ 
    __init__.py 
    models.py 
    views.py 
    templatetags/ 
    __init__.py 
    nav_active.py 
+0

我是django的新手,所以我不確定在哪裏放置nav_active.py文件。我將它放在已安裝應用程序的目錄中,但出現以下錯誤:'nav_active'不是已註冊的標記庫。必須是以下其中一項:admin_list admin_modify admin_static admin_urls cache future i18n l10n log static staticfiles tz。我應該在哪裏放置nav_active.py文件? – tonryray

+0

更新了額外的信息,希望這會有所幫助。 –

+0

真棒!是的,我的忍者過濾器現在可以工作。非常感謝。 – tonryray