Django 基于 URL 显示列表项
Django display list items based on URL
我正在尝试 hide/show 我的导航部分,具体取决于我的活动 URL。
我曾尝试使用 re.match()
方法来做到这一点,但 jinja 不喜欢这样。此代码位于我的侧面导航的 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>
提前致谢。
您可以创建一个 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
我正在尝试 hide/show 我的导航部分,具体取决于我的活动 URL。
我曾尝试使用 re.match()
方法来做到这一点,但 jinja 不喜欢这样。此代码位于我的侧面导航的 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>
提前致谢。
您可以创建一个 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