2011-06-28 46 views
1

每次向我的應用程序發出請求時,我都會使用中間件來檢索並存儲具有與特定頁面相關的信息的「頁面」對象。我存儲請求對象這個對象的引用,這裏有一個例子:模板標記和請求對象

class PageMiddleware(object): 
    def process_request(self, request): 
     if not hasattr(request, 'page'): 
      request.page = Page.objects.get(slug=<slug>) 
     return None 

它的工作原理不夠好,但我想在一個模板標籤訪問該對象。模板標籤只能引用'context'思想,這意味着我無法看到我的Page對象。

我知道我可以使用自定義上下文處理器爲此,但這意味着進一步修改設置文件,我想盡量保持此應用程序儘可能封裝。例如,我注意到,調試工具欄應用程序管理將數據附加到模板上下文而無需修改TEMPLATE_CONTEXT_PROCESSORS。

簡而言之,我想通過僅使用中間件來訪問模板標記中的頁面對象。有任何想法嗎?

編輯:我使用的是標準的模板標籤,下面的類:

class GetPageContentNode(Node): 
    def __init__(self, key): 
     self.key = key 

    def render(self, context): 
     return context['request'].page 

回答

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

+0

感謝您的答覆。我應該在我的原文中說過我使用的是標準標籤而不是包含標籤。調用上下文['請求']導致鍵錯誤。 – Hanpan

+0

它也應該在普通模板標籤上工作。包含&簡單模板標籤只是普通模板標籤的包裝器 –

1

通話每render_to_responsecontext_instance參數,如:

def some_view(request): 
    # ... 
    return render_to_response('my_template.html', 
          my_data_dictionary, 
          context_instance=RequestContext(request)) 

編輯者:Daniel Roseman爲sugested:

並添加django.core.context_processors.requestTEMPLATE_CONTEXT_PROCESSORS設置。

+1

實際上,您不需要第二部分 - 已經有[請求上下文處理器](https://docs.djangoproject.com/en/1.3/ ref/templates/api /#django-core-context-processors-request),不過你需要在settings.py中專門啓用它。 –

+0

@Daniel:完美。 –

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