2017-04-27 46 views
0

我在模板中有一些鏈接。如何將指定的kwargs設置爲url外部for循環?

<ul> 
    {% for cat in cats %} 
     <li><a href="{% url 'c_index' cat.slug %}">{{ cat.name }}</a> 
    {% endear %} 
</ul> 
<ul> 
    {% for type in types %} 
     <li><a href="{% url 'ct_index' cat.slug type.slug %}">{{ type.name }}</a> 
    {% endear %} 
</ul> 

當然,因爲我不能{貓%%貓}循環使用「cat.slug」之外我無法訪問第二個鏈接。

但是我想在不使用{cat for cats%}循環的情況下將「cat.slug」設置爲第二個鏈接。

我該怎麼做?例如,使用模板標籤?

url(r'^c_(?P<cat>[-\w]+)/$', views.c_index, name='c_index'), 
url(r'^c_(?P<cat>[-\w]+)/t_(?P<type>[-\w]+)/$', views.ct_index, name='ct_index'), 

def c_index(request, cat): 
    c = {} 

    posts = Post.objects.filter(category__slug=cat) 
    cats = Category.objects.all() 

    c.update({ 
     'posts': posts, 
     'cats': cats, 
    }) 

    return render(request, 'classifieds/index.html', c) 

def ct_index(request, cat, type): 
    c = {} 

    posts = Post.objects.filter(category__slug=cat).filter(type=type) 
    cats = Category.objects.all() 
    types = Types.objects.all() 

    c.update({ 
     'posts': posts, 
     'cats': cats, 
     'types': types, 
    }) 

    return render(request, 'classifieds/index.html', c) 
+0

你想讓貓的第二個鏈接出現在你的貓列表中,或者只是一隻貓嗎?如果只是一隻貓,你怎麼知道哪一隻? – ChidG

+0

只是一隻貓。我想要一個內部當前網址用於第二個鏈接。 url(r'^ c _(?P [ - \ w] +)/ $',views.c_index,name ='c_index') – Mickey

+0

您可以發佈您的視圖代碼嗎? – ChidG

回答

0

在您的意見中,您需要添加category = Category.objects.get(slug=cat)。然後將category變量添加到您的上下文中。 然後在您的模板中,您可以使用您在上下文中定義的模板變量來訪問該類別。如果是category,您的url標記將如下所示:{% url 'ct_index' category.slug type.slug %}

相關問題