开发者

django - what's the proper way of passing the "request" parameter to a custom template tag

开发者 https://www.devze.com 2023-04-08 17:36 出处:网络
I created a custom template tag that I want to use on every page on my web site.I have a function get_ip inside the custom template tag that needs the request parameter in order to get the IP address

I created a custom template tag that I want to use on every page on my web site. I have a function get_ip inside the custom template tag that needs the request parameter in order to get the IP address from the user. See below:

myapp/templatetags/header_tags.py


from django import template
register = template.Library()
...
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

@register.inclusion_tag('template.html', takes_context = True)
def user_ip(context):
    request = context['r开发者_StackOverflow中文版equest']
    ip = get_ip(request)      
    return render_to_response('template.html',locals(), context_instance=RequestContext(request))

template.html


   {{ ip }}

my_main_template.html


{% load header_tags %}
{% user_ip %} 

For some reason my the ip is not sowing on my main template. My function get_ip works if used the regular way on views.py page a template but for some reason is not showing when is used from the custom template tag above. Any ideas?


You're not supposed to actually render the template in an inclusion tag - the decorator does that for you. You just return the context that should be used to render the template you've specified.


Try somenting like this.

@register.inclusion_tag('template.html', takes_context = True)
def user_ip(context):
    return {'ip': get_ip(context['request'])}


Your inclusion tag should return a context to be rendered to a template, not render_to_response. Might look like this:

def user_ip(context):
    my_context = {}
    request = context['request']
    my_context['ip'] = get_ip(request)      
    return my_context

register.inclusion_tag('template.html', takes_context = True)(user_ip)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号