Django 从当前 URL 获取根路径

时间:2021-01-06 21:08:08

标签: python html django django-templates wagtail

我正在使用 Wagtail CMS 开发 Django 网站。我在页面顶部有一个导航栏,其中使用模板标签,它循环浏览 navigation 变量中的页面。

{% for item in navigation.menu_items.all %}
    <a class="nav-link {% if request.get_full_path == item.link %}active{% endif %}" href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank"{% endif %}>{{ item.title }}</a>
{% endfor %}

假设 URL 为 http://localhost:8000/blog/ 且页面 URL 相同,然后将 active 类应用于该迭代。

当我在具有 http://localhost:8000/blog/example-blog-post/ 等 URL 的页面上时出现问题,这与 http://localhost:8000/blog/ 不匹配并且未应用活动类,即使我在博客中也是如此。< /p>

有没有办法去掉 URL 只保留根路径,让 http://localhost:8000/blog/example-blog-post/ 变成 http://localhost:8000/blog/,这样活动类就可以应用于目录中的子页面了?

2 个答案:

答案 0 :(得分:1)

您可以使用 slice 过滤器

{% if request.path|slice:":5" == item.link %} active{% endif %}

您可以使用 in 运算符。

所以改为 {% if request.get_full_path == item.link %}{% if item.link in request.get_full_path %} 或抓住主页 {% if request.get_full_path in item.link and request.get_full_path != '/' or request.get_full_path == item.link %}

答案 1 :(得分:0)

这可能不是最有效的方法,但目前对我来说,这是唯一的方法。

我创建了一个自定义模板标签,它接受上下文和菜单项对象,如果当前 URL 与导航项(项目)的 URL 匹配,则返回 active 类名

在 HTML 中,当每个导航项被迭代时,项被传递给 get_active 方法(我制作的自定义模板标签)

{% load menu_tags %}
{% get_menu "MAIN" as navigation %}
{% for item in navigation.menu_items.all %}
    {% get_active item as active_class %}
    <a class="nav-link {{ active_class }}" href="{{ item.link }}" {% if item.open_in_new_tab %} target="_blank"{% endif %}>{{ item.title }}</a>
{% endfor %}

模板标签:

@register.simple_tag(takes_context=True)
def get_active(context, item):
    request = context['request']
    currentURL = request.path
    linkURL = item.link
    currentURLStripped = str(currentURL).replace("/", "")
    linkURLStripped = str(linkURL).replace("/", "")
    if linkURLStripped=="" and currentURLStripped=="":
        return "active"
    elif linkURLStripped in currentURLStripped and linkURLStripped!="":
        return "active"
    else:
        return ""

上面的代码只是获取用户当前所在页面的 URL,例如,如果用户在 http://localhost:8000/blog 上,那么 currentURL 将是 /blog/linkURLitem 对象的 URL 属性,对于链接到联系我页面的项目对象,其 URL 属性将为 /contact-me/,因此 linkURL 将是一样的。

该方法只是从 URL 字符串中去除“/”。如果 URL 用于主页(即它是 /),则该变量将为空。 if linkURLStripped=="" and currentURLStripped=="": 捕获主页。

elif linkURLStripped in currentURLStripped and linkURLStripped!="": 捕获其他页面并忽略主页。

相关问题