简体   繁体   English

我可以在django模板上下文处理器中访问url kwargs吗?

[英]Can I access url kwargs in django template context processor?

urls.py

url(r'^(?i)(?P<slug>[a-zA-Z0-9_]+)$', views_search.index, name='articles'),

context_processor.py context_processor.py

def get_username(request, **kwargs):
    print kwargs
    slug = kwargs.get('slug')
    return {
    'slug': slug
    }

But when i am running it, its printing empty dict and nothing is returned to the template. 但是当我运行它时,它打印空字典并且没有任何内容返回到模板。 I have added this in template context processors in setting. 我在设置中的模板上下文处理器中添加了这个。 How can I access kwargs here ? 我怎么能在这里访问kwargs?

If an url is resolved, the ResolverMatch object is set as an attribute on the request: 如果解析了URL,则将ResolverMatch对象设置为请求的属性:

def get_username(request):
    if hasattr(request, 'resolver_match'):
        slug = request.resolver_match.kwargs.get('slug')
        return {'slug': slug}
    return {}

Actually, for class based views, the view is already available in the context, so you can directly access kwargs in the template. 实际上,对于基于类的视图, view已在上下文中可用,因此您可以直接访问模板中的kwargs In the template, just do the following: 在模板中,只需执行以下操作:

{{ view.kwargs.slug }}

Also, see this SO answer 另外,请看这个 SO答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM