我在我的網站上的每個頁面上創建了一個自定義模板標記。我有一個函數get_ip在自定義模板標記內,需要請求參數以便從用戶獲取IP地址。請看下圖:django - 將「請求」參數傳遞給自定義模板標記的正確方法
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['request']
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 %}
出於某種原因,我的IP是不是我的主模板播種。我的功能get_ip如果使用常規方法在views.py頁面上使用模板,但出於某種原因不能顯示何時從上面的自定義模板標記中使用。有任何想法嗎?
因此,而不是使用「return render_to_response(...)」我應該只使用return {'ip':ip}? – avatar
就是這樣。謝謝! – avatar