比较request.path和Django模板中的反向URL [英] Compare request.path with a reversed url in Django template

查看:38
本文介绍了比较request.path和Django模板中的反向URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 request.path 会给我当前的URL。

I understand that request.path will give me the current URL.

我目前正在处理我的 base.html 带有CSS选项卡的模板,我希望模板知道哪个选项卡当前处于活动状态并传递 class = active-tab < a> 标记。

I am currently working on my base.html template with CSS tabs and I want the template to know which tab is currently "active" and pass class="active-tab" to an <a> tag.

所以我想做类似的事情

<a href="{% url orders_list %}"
    {% if request.path = reverse('orders_list') %}
        class="active-tab"
    {$ endif %}
>Orders</a>

但是我敢肯定,如果比较。我也只希望基本(?)URL忽略任何GET参数。

But I'm sure you can't do that if comparison. I also only want the base (?) URL ignoring any GET parameters.

也欢迎任何建议或技巧。

Any suggestions or tips also welcomed. Thanks in advance!

推荐答案

您可以使用自定义模板标签

from django import template

register = template.Library()

@register.simple_tag
def active(request, pattern):
    path = request.path
    if path == pattern:
        return 'active'
    return ''

然后您的模板中的用法如下:

Then usage is sort of like this in your template:

{% load my_tags %}

{% url orders_list as orders %}
<li class="{% active request orders %}"> 
    <a href="{{ orders }}"> Orders </a> 
</li>

您可以根据需要修改模板标记。

You can modify the template tag as you wish.

这篇关于比较request.path和Django模板中的反向URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆