Accessing global variable in view using context processor in Django

前端 未结 3 1542
忘了有多久
忘了有多久 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:06

    Add your context processor method path (folder.context_processor.application_context) to TEMPLATE_CONTEXT_PROCESSORS.

    in my case application_context is the method which i defined inside file context_processor.py and method "application_context" returns {'titles': 'mytitle'}

    if you want to use "title" as global variable in views use it in this way

    global_var = RequestContext(request).get("app_config")
    titles = global_var.get("titles")
    print titles 
    

    The only advantage is "Same variable 'titles' will be visible for templates and also in your views"

提交回复
热议问题