2017-07-08 111 views
0

我試圖在包含標記模板中使用request.path,但URL不顯示。 request.path在父模板中使用時可以正常工作,並且包含標籤在所有其他位置都可以正常工作。 我在包含標記中啓用了'takes_context',但我不知道在views.py中是否以及在哪裏應指定任何特定於路徑的上下文。 目前我使用從我views.py渲染()方法輸出的邏輯:Django request.path不能在包含標記模板中工作

def DJ_LastDay(request): 
    p = Post.objects.latest('Day') 
    posts = Post.objects.filter(Day=p.Day) 
    return render(request, 'blog/DJ_LastDay.html', {'DJ_LastDay_posts': posts}) 

摘錄我的包容標籤:

我包含標籤模板
from django import template 
register = template.Library() 
@register.inclusion_tag('blog/index_table.html', takes_context=True) 
def DJ_LastDay(context): 
    return {'posts': context['DJ_LastDay_posts']} 

片段(DJLD,DJLW,DJLM ,DJLQ和DJLY都是URL快捷方式我父模板中啓用,它們包含模板外做工精細):

{% if request.path == DJLD %} 
     Last Day 
    {% elif request.path == DJLW %} 
     Last Week 
    {% elif request.path == DJLM %} 
     Last Month 
    {% elif request.path == DJLQ %} 
     Last Quarter 
    {% elif request.path == DJLY %} 
     Last Year 
    {% endif %} 

我只需要檢測當前路F或者使用條件檢查在我的模板中顯示正確的字符串。 任何幫助表示讚賞

回答

1

您必須通過要求使用inclusion_tag模板就像你在沒有回報的帖子「

@register.inclusion_tag('blog/index_table.html', takes_context=True) 
def DJ_LastDay(context): 
    return {'posts': context['DJ_LastDay_posts'], 'request':context['request']} 
+0

謝謝NeErAj,我可以得到Request的關聯,現在顯示網址,但由於某種原因,我似乎無法將request.path生成的url與之前創建的url快捷方式(在父模板中正常工作)進行比較。 {%if request.path%}返回true,但它似乎不符合我以前使用的任何快捷鍵(DJLD,DJLW等....) – cqcum6er