2012-04-21 27 views
4

我知道request.path会给我当前的URL。将request.path与Django模板中的反向网址进行比较

我目前的工作对我base.html模板,CSS标签,我想模板知道哪个选项卡是当前“活动”,并通过class="active-tab"<a>标签。

,所以我想这样做

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

但我敢肯定,你不能这样做,if比较。我也只想要基础(?)URL忽略任何GET参数。

任何建议或提示也欢迎。提前致谢!

回答

3

您可以使用一个custom template tag

from django import template 

register = template.Library() 

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

然后使用是有点像这样在你的模板:

{% load my_tags %} 

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

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

1

您可以在视图中计算任何需要的东西(例如request.path = reverse('orders_list')),并将结果传递给模板。在视图(Python代码)中,您可以尽可能多地操作路径。

您可以检查一个URL是否是另一个的前缀。

0

我想通过jQuery实现黑客攻击的方式......但我仍然对更好的解决方案开放。

的jQuery:

var tab_list = { 
    'orders-tab' : '{% url orders_list %}', 
    'users-tab' : '{% url users_list %}', 
    'vendors-tab': '{% url vendors_list %}', 
    'places-tab' : '{% url places_list %}' 
} 

$(document).ready(function() { 
    for(var property in tab_list) { 
     if('{{ request.path }}' == tab_list[property]) { 
      $('#' + property).addClass('active-tab') 
      break 
     } 
    } 
}) 

HTML:

<ul id="tabs" class="fl"> 
    <li><a href="#" id="dashboard-tab" class="dashboard-tab">Dashboard</a></li> 
    <li><a href="{% url orders_list %}" id="orders-tab">Orders</a></li> 
    <li><a href="{% url users_list %}" id="users-tab">Users</a></li> 
    <li><a href="{% url vendors_list %}" id="vendors-tab">Vendors</a></li> 
    <li><a href="{% url places_list %}" id="places-tab">Places</a></li> 
</ul> 
1

试试这个jQuery的语句:

$("[href='{{ request.path }}']").parents("li").addClass('active'); 
2

由美洲狮的回答启发:

$("ul.nav [href='"+window.location.pathname+"']").parents("li").addClass('active'); 

该解决方案是简单的JS,并适用于引导的导航栏。对于OP的情况下可以使用:

$("[href='"+window.location.pathname+"']").addClass('active-tab'); 
10

大厦Josh的回答,您可以使用“如果”标签的简单:

{% url 'orders_list' as orders_list_url %} 
<a{% if request.path == orders_list_url %} class="active"{% endif %} 
    href="{{ orders_list_url }}">Orders</a> 
+0

不错!而且不需要自定义模板标签! – Inti 2016-12-15 10:54:04

2

一个更好的版本最多的回答将是扭转视图名:

{% url_active 'reverse_viewname' %} 

此版本不要求您传入request。相反,我们指出标签需要上下文,然后从中获取请求。

from django import template 
from django.core.urlresolvers import reverse 

register = template.Library() 

@register.simple_tag(takes_context=True) 
def url_active(context, viewname): 
    request = context['request'] 
    current_path = request.path 
    compare_path = reverse(viewname) 
    if current_path == compare_path: 
     return 'active' 
    else: 
     return '' 
1

用法:{% url_active "home" "other-view" "and-so-on" success="active-specific-class" %}

from django import template 

register = template.Library() 


@register.simple_tag(takes_context=True) 
def url_active(context, *args, **kwargs): 
    if 'request' not in context: 
     return '' 

    request = context['request'] 
    if request.resolver_match.url_name in args: 
     return kwargs['success'] if 'success' in kwargs else 'active' 
    else: 
     return '' 
2

与IF-THEN-ELSE选项:A液

from django import template 
from django.template.base import Node, NodeList, TemplateSyntaxError 

register = template.Library() 

class IfCurrentViewNode(Node): 
    child_nodelists = ('nodelist_true', 'nodelist_false') 

    def __init__(self, view_name, nodelist_true, nodelist_false): 
     self.view_name = view_name 
     self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false 

    def __repr__(self): 
     return "<IfCurrentViewNode>" 

    def render(self, context): 
     view_name = self.view_name.resolve(context, True) 
     request = context['request'] 
     if request.resolver_match.url_name == view_name: 
      return self.nodelist_true.render(context) 
     return self.nodelist_false.render(context) 


def do_ifcurrentview(parser, token): 
    bits = token.split_contents() 
    if len(bits) < 2: 
     raise TemplateSyntaxError("'%s' takes at least one argument" 
            " (path to a view)" % bits[0]) 
    view_name = parser.compile_filter(bits[1]) 
    nodelist_true = parser.parse(('else', 'endifcurrentview')) 
    token = parser.next_token() 
    if token.contents == 'else': 
     nodelist_false = parser.parse(('endifcurrentview',)) 
     parser.delete_first_token() 
    else: 
     nodelist_false = NodeList() 
    return IfCurrentViewNode(view_name, nodelist_true, nodelist_false) 

@register.tag 
def ifcurrentview(parser, token): 
    """ 
    Outputs the contents of the block if the current view match the argument. 

    Examples:: 

     {% ifcurrentview 'path.to.some_view' %} 
      ... 
     {% endifcurrentview %} 

     {% ifcurrentview 'path.to.some_view' %} 
      ... 
     {% else %} 
      ... 
     {% endifcurrentview %} 
    """ 
    return do_ifcurrentview(parser, token) 
+0

我们的代码很棒。有没有办法为此写一些简单的测试用例?我想保持我们的测试覆盖率。写了一个SO问题,正是这个请求在https://stackoverflow.com/questions/47534145/how-to-write-a-test-case-for-this-django-custom-tag – 2017-11-28 14:34:15

+0

我想这是可测试的。不知道如何。你应该看看Django如何测试它的标签(例如https://github.com/django/django/blob/3c447b108ac70757001171f7a4791f493880bf5b/tests/template_tests/tests.py#L104) – zigarn 2017-11-28 19:50:09

相关问题