【问题标题】:django - what's the proper way of passing the "request" parameter to a custom template tagdjango - 将“请求”参数传递给自定义模板标签的正确方法是什么
【发布时间】:2011-11-24 09:23:18
【问题描述】:

我创建了一个自定义模板标签,我想在我网站的每个页面上使用它。我在自定义模板标签中有一个函数 get_ip 需要 request 参数才能从用户那里获取 IP 地址。见下文:

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 没有在我的主模板上播种。如果在views.py页面模板上使用常规方式,我的函数get_ip可以工作,但由于某种原因没有显示何时从上面的自定义模板标签中使用。有什么想法吗?

【问题讨论】:

    标签: django django-views django-templates


    【解决方案1】:

    您不应该在包含标签中实际渲染模板 - 装饰器会为您执行此操作。您只需返回应该用于呈现您指定的模板的上下文。

    【讨论】:

    • 所以我应该使用 return {'ip':ip } 而不是使用“return render_to_response(...)”?
    【解决方案2】:

    试试这样的感觉。

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

    【讨论】:

      【解决方案3】:

      您的包含标签应返回要呈现给模板的上下文,而不是render_to_response。可能看起来像这样:

      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)
      

      【讨论】:

        猜你喜欢
        • 2014-07-14
        • 2023-03-24
        • 1970-01-01
        • 2014-05-13
        • 2023-03-20
        • 2021-09-04
        • 2011-06-17
        • 1970-01-01
        • 2019-10-30
        相关资源
        最近更新 更多