【问题标题】:Get list of all URL names in Django to make Active links in Navigation获取 Django 中所有 URL 名称的列表以在导航中创建活动链接
【发布时间】:2020-01-15 09:00:33
【问题描述】:

我正在为导航栏中的活动/当前访问的链接放置一个模板标签,这样我就可以轻松地将适当的活动 CSS 类添加到链接中。

我创建的代码适用于包含相同 url 参数的传入 url 的混合,但它不允许我传入具有不同参数的 url。

{% make_active 'index' %} 和 {% make_active 'users' 1 %} 无法准确组合为 {% make_active 'index~users' 1 %},因为我正在使用 reverse() 来查看 url 是否存在。

我想要的只是检查项目中每个 url 模式文件的名称,如果名称存在,则返回适当的活动类……但我不知道如何简单地获取名称。这可能吗,或者有人可以帮助编写代码吗?

@register.simple_tag(takes_context=True)
def make_active(context, view_names, *args, **kwargs):
    print(args, kwargs)
    if not kwargs.pop('class', None):
        class_to_return = 'sidebar-item-active'
    else:
        class_to_return = kwargs.pop('class')

    request = context.get('request')

    if not request:
        raise Exception('A request must be passed in for this to work')

    names = view_names.split('~')
    print(names)
    current_url_active = False
    for view in names:
        print(view)
        try:
            # always include the client url
            args_to_use = [request.client_url]
            # append the passed args into the args for reversing the url name
            args_to_use.extend(args)
            reversed_path = reverse(view, args=args_to_use)
            print(reversed_path)
            current_url_active = True
        except NoReverseMatch:
            current_url_active = False
            continue

        if current_url_active:
            break

    return class_to_return if current_url_active else None

【问题讨论】:

    标签: django python-3.x django-templates


    【解决方案1】:

    我想出了一种使用动态导入来收集 url 名称的方法,但是在弄清楚我想要做什么之后,我了解到我什至不需要经历收集所有 url 名称的复杂性。无论如何,这是代码:

    def get_url_names():
        from django.apps import apps
    
        list_of_url_names = list()
        list_of_all_urls = list()
        for name, app in apps.app_configs.items():
            mod_to_import = f'apps.{name}.urls'
            try:
                urls = getattr(importlib.import_module(mod_to_import), "urlpatterns")
                list_of_all_urls.extend(urls)
            except ImportError as ex:
                # is an app without urls
                pass
        for url in list_of_all_urls:
            list_of_url_names.append(url.name)
    
        return list_of_url_names
    

    在完成这项工作时,我发现我需要检查的只是我是否在当前的 url 名称上,这很容易通过 request.path_info 收集。所以现在我的代码可以这样改变了

    @register.simple_tag(takes_context=True)
    def make_active(context, view_names, *args, **kwargs):
    
        if not kwargs.get('class', None):
            class_to_return = 'sidebar-item-active'
        else:
            class_to_return = kwargs.get('class')
    
        request = context.get('request')
    
        if not request:
            raise Exception('A request must be passed in for this to work')
    
        names = view_names.split('|')
        current_url_name = resolve(request.path_info).url_name
        for view in names:
            if view == current_url_name:
                return class_to_return
    
    

    现在我可以使用我的 url 标签返回正确的活动链接 CSS 类,如下所示:

     <div class="collapse {% make_active 'users_index|users_actions|groups_index|groups_edit|users_create' class='show' %} " id="userCollapse">
    
        <div class="card card-body">
            {% if perms.users.view_customuser and perms.users.view_staff %}
                <a class="dropdown-item {% make_active 'users_create|users_index|users_actions' %}"
                   href="{% url 'users_index' CLIENT.url_base %}"><i
                        class="fas fa-users"></i>
                    <span class="nav-item-text">&nbsp;Users</span>
                </a>
            {% endif %}
            {% if perms.auth %}
                <div class="dropdown-divider"></div>
                <a class=" dropdown-item {% make_active 'groups_index|groups_edit' %}"
                   href=" {% url 'groups_index' CLIENT.url_base %}">
                    <i class="far fa-user-plus"></i>
                    <span class="nav-item-text">&nbsp;Group Permissions</span>
                </a>
            {% endif %}
        </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2023-02-26
      • 2016-05-02
      • 2021-05-07
      • 1970-01-01
      • 2018-03-18
      • 2021-11-12
      • 2021-05-07
      • 1970-01-01
      • 2021-05-22
      相关资源
      最近更新 更多