Django模板:将当前网址与{%url xyz%}进行比较

sup*_*er9 11 django django-templates

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

我想做这样的事情:

<li {% if request.get_full_path == {% url profile_edit_personal %} %}class="current"{% endif %}><a href="{% url profile_edit_personal %}">Personal Details</a></li>
Run Code Online (Sandbox Code Playgroud)

或者,我知道我可以定义这样的事情:

<li class="{% block current %}{% endblock %}"><a href="{% url profile_edit_personal %}">Personal Details</a></li>
Run Code Online (Sandbox Code Playgroud)

并添加{% block current %}current{% endblock %}到每个相关的模板,但我更喜欢像我试图在第一个例子中实现的东西,如果可能的话

谢谢!

nul*_*ity 17

由于您可能只需要执行一次 - 在导航模板中 - 因此将所有内容保存在一个位置对我来说更有意义.

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

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

<ul id="nav">
    <li class="{% ifequal request.path about %}active{% endifequal %}"><a href="{{about}}">About</a></li>
...
Run Code Online (Sandbox Code Playgroud)

只需确保启用了请求上下文处理器,以便您可以访问模板中的请求.通过添加django.core.context_processors.debug您的TEMPLATE_CONTEXT_PROCESSORS设置变量来执行此操作.


Tim*_*ony 6

这是一个非常常见的要求,因此编写自己的模板标签来执行此操作可能是值得的:

class isCurrentNode(template.Node):
    def __init__(self, patterns):
        self.patterns = patterns
    def render(self, context):
        path = context['request'].path
        for pattern in self.patterns:
            curr_pattern = template.Variable(pattern).resolve(context)
            if path == curr_pattern:
        return "current"
            return ""

@register.tag
def is_current(parser, token):
    """ Check if the browse is currently at this supplied url"""
    args = token.split_contents()
    if len(args) < 2:
        raise template.TemplateSyntaxError, "%r tag requires at least one argument" % args[0]
    return isCurrentNode(args[1:])
Run Code Online (Sandbox Code Playgroud)

并在您的模板中

{% url about_page as about %}
{% url home_page as home %}
...

<ul>
    <li class="{% is_current home %}"><a href="{{ home }}">Home</a></li>
    <li class="{% is_current about %}"><a href="{{ about }}">About</a></li>
    ...
Run Code Online (Sandbox Code Playgroud)

这里的想法略有不同:

http://gnuvince.wordpress.com/2007/09/14/a-django-template-tag-for-the-current-active-page/ http://www.turnkeylinux.org/blog/django-navbar