关于python:Django request.path在包含标记模板中不起作用

Django request.path not working in inclusion tag template

我尝试在包含标记模板中使用request.path,但未显示网址。当在父模板中使用时,request.path可以正常工作,而include标记在所有其他位置也可以正常工作。
我在包含标记中启用了" takes_context",但我不知道是否应该在views.py中以及在何处指定任何特定于路径的上下文。
目前,我使用render()方法从我的views.py:

输出逻辑

1
2
3
4
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})

我的包含标签的代码段:

1
2
3
4
5
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快捷方式,它们在包含模板之外都可以正常使用)的代码段:

1
2
3
4
5
6
7
8
9
10
11
    {% 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 %}

我只需要检测当前路径即可进行条件检查,以在模板中显示正确的字符串。
任何帮助表示赞赏


您必须像将\\'posts \\'一样将请求传递给include_tag模板,以作为回报

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