您可以创建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
我是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
更新了额外的信息,希望这会有所帮助。 –
真棒!是的,我的忍者过滤器现在可以工作。非常感谢。 – tonryray