每次向我的应用程序发出请求时,我都会使用中间件检索并存储一个“页面”对象,该对象具有与该特定页面相关的信息。我在请求对象中存储对此对象的引用,这是一个示例:
class PageMiddleware(object):
def process_request(self, request):
if not hasattr(request, 'page'):
request.page = Page.objects.get(slug=<slug>)
return None
它运行良好,但我想在模板标签中访问此对象。模板标签只有对“上下文”思想的引用,这意味着我无法看到我的Page对象。
我知道我可以使用自定义上下文处理器,但这意味着进一步修改设置文件,我想尝试将此应用程序尽可能地封装起来。例如,我注意到Debug Toolbar应用程序设法将数据附加到模板上下文而不修改TEMPLATE_CONTEXT_PROCESSORS。
简而言之,我想通过仅使用中间件来理想地访问模板标签中的Page对象。有什么想法吗?
编辑:我使用的是标准模板标记,包含以下类:
class GetPageContentNode(Node):
def __init__(self, key):
self.key = key
def render(self, context):
return context['request'].page
答案 0 :(得分:2)
看看这个,你可以通过在注册模板标签时传递takes_context来访问请求对象(和你的对象)
Access request in django custom template tags
在此页面上搜索“takes_context”:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#registering-the-tag
答案 1 :(得分:1)
使用context_instance参数调用每个render_to_response
,例如:
def some_view(request):
# ...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
按Daniel Roseman的建议编辑:并将django.core.context_processors.request添加到TEMPLATE_CONTEXT_PROCESSORS设置。
答案 2 :(得分:0)
试试这个:
class GetPageContentNode(Node):
def __init__(self, key):
self.key = key
def render(self, context):
request = template.Variable('request').resolve(context) # here's the magic!
return request.page