2016-07-25 69 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