2012-04-21 14 views
4

私はrequest.pathが私に現在のURLを与えることを理解します。Djangoテンプレートの逆URLでrequest.pathを比較してください

私は現在、CSSタブで私のbase.htmlテンプレートに取り組んでいると私は、テンプレートが現在「アクティブ」であるタブを知り、<a>タグにclass="active-tab"を渡したいです。

だから私は

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

のようなものをやってみたかったしかし、私はあなたがそのif比較を行うことはできません確信しています。私はまた、GETパラメータを無視して、ベース(?)URLだけを必要とします。

いずれの提案やヒントも歓迎します。前もって感謝します!

答えて

3

その後の使用は、あなたのテンプレートでの並べ替えのこのようなものです:

{% 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:あなたは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 '' 

を使用することができます

<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で、ブートストラップのナビゲーションバーで働いています。ジョシュの答えのビル

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

タグ「が」、あなたは簡単なを使用することができます:1を使用することができOPのシナリオのためのトップの答えの

{% 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

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オプションとソリューション:

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

のurコードは素晴らしい動作します。これには簡単なテストケースを書く方法がありますか?テストカバレッジのパーセンテージを維持したい。 https://stackoverflow.com/questions/47534145/how-to-write-a-test-case-for-this-django-custom-tag –

+0

私はそれがテスト可能だと思います。どのように知りません。 Djangoがタグをどのようにテストするかを見てください(例:https://github.com/django/django/blob/3c447b108ac70757001171f7a4791f493880bf5b/tests/template_tests/tests.py#L104) – zigarn

関連する問題