获取Django中所有URL名称的列表,以在导航中创建活动链接

oug3syen  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(102)

我把一个模板标签的活动/当前访问的链接在一个导航栏,所以我可以很容易地添加适当的活动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
zte4gxcn

zte4gxcn1#

我想出了一个使用动态导入来收集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

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

<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>

相关问题