Django模板:将当前网址与{%url xyz%}进行比较 [英] Django Templates: Comparing current url with {% url xyz %}

查看:58
本文介绍了Django模板:将当前网址与{%url xyz%}进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据用户所在的当前页面更改导航链接的活动选择。

I am trying change the active selection of my navigation links based on the current page where the user is at.

我正在尝试执行以下操作:

I am trying to do omething like this:

<li {% if request.get_full_path == {% url profile_edit_personal %} %}class="current"{% endif %}><a href="{% url profile_edit_personal %}">Personal Details</a></li>

或者,我知道我可以定义执行以下操作:

Alternatively, I know I could define do something like this:

<li class="{% block current %}{% endblock %}"><a href="{% url profile_edit_personal %}">Personal Details</a></li>

并添加 {%block current%} current {%endblock%} 到每个相关模板,但是我更喜欢像Im在第一个示例中尝试实现的东西

and add a {% block current %}current{% endblock %} to each of the relevant templates but I would prefer something like what Im trying to achieve in the first example if possible

谢谢!

推荐答案

由于您可能只需要执行一次此操作(在您的导航模板中),对我来说保留所有内容就更有意义了

Since you'll probably only need to do this once--in your nav template--it makes more sense to me to keep everything in one place.

首先反转您的url名称,并将其存储在Timmy建议的变量中,然后只需在模板中进行比较即可:

First reverse your url names and store them in variables like Timmy suggested, then simply compare them in the template:

{% url 'about_page' as about %}
...

<ul id="nav">
    <li class="{% ifequal request.path about %}active{% endifequal %}"><a href="{{about}}">About</a></li>
...

只要确保已启用请求上下文处理器,就可以访问模板中的请求。为此,可在 TEMPLATE_CONTEXT_PROCESSORS 设置变量中添加 django.core.context_processors.debug

Just make sure you have your request context processor enabled so you have access to the request in the template. Do this by adding django.core.context_processors.debug in your TEMPLATE_CONTEXT_PROCESSORS settings variable.

这篇关于Django模板:将当前网址与{%url xyz%}进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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