Accessing global variable in view using context processor in Django

前端 未结 3 1521
忘了有多久
忘了有多久 2021-01-13 03:17

Assuming I have a context processor:

def title(request):
   return {\'titles\': \'mytitle\'}

I can access this variable in template as

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-13 04:15

    Context processors aren't in any way global variables. They are simply functions that are run when a RequestContext is initiated, which add items to that context. So they're only available wherever you have a RequestContext, ie in a template.

    Your examples don't really give a good idea of what variables you're looking to access. If it's just some constants you want to use everywhere, a good way is to define them somewhere central, say in settings.py, and import that module wherever you need it - plus use a context processor to add them to the context.

提交回复
热议问题