cqcum6er
cqcum6er

Reputation: 57

Django request.path not working in inclusion tag template

I tried to use request.path in the inclusion tag template, but the url does not show up. The request.path does work properly when used in parent template, and the inclusion tag works properly in all other places. I enabled 'takes_context' in the inclusion tag, but I don't know if and where I should specify any path-specific context in the views.py. Currently I use render() method to output the logic from my views.py:

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}) 

Snippet of my inclusion tag:

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']}

Snippet of my inclusion tag template (DJLD, DJLW, DJLM, DJLQ, and DJLY are all url shortcuts I enabled in the parent template, and they work fine outside the inclusion template):

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

I just needed to detect the current path for a conditional check to display the proper string in my template. Any help is appreciated

Upvotes: 0

Views: 1168

Answers (1)

Neeraj Kumar
Neeraj Kumar

Reputation: 3941

You have to pass request to inclusion_tag template like you did 'posts' in return

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

Upvotes: 3

Related Questions