What is a context in Django?

孤街醉人 提交于 2019-11-26 10:26:56

问题


I\'m a django beginner so I\'m trying to understand the concept of context and context processor.

  • What is a context and why do you use it?
  • Is a context a value you need to have available in order to use in a template?
  • Is a context and a context processor the same?

I\'ll apreciate a lot your response. Thanks in advance!


回答1:


When you use a Django Template, it is compiled once (and only once) and stored for future use, as an optimization. A template can have variable names in double curly braces, such as {{ myvar1 }} and {{ myvar2 }}.

A Context is a dictionary with variable names as the key and their values as the value. Hence, if your context for the above template looks like: {myvar1: 101, myvar2: 102}, when you pass this context to the template render method, {{ myvar1 }} would be replaced with 101 and {{ myvar2 }} with 102 in your template. This is a simplistic example, but really a Context object is the context in which the template is being rendered.

As for a ContextProcessor, that is a slightly advanced concept. You can have in your settings.py file listed a few Context Processors which take in an HttpRequest object and return a dictionary (similar to the Context object above). The dictionary (context) returned by the Context Processor is merged into the context passed in by you (the user) by Django.

A use case for a Context Processor is when you always want to insert certain variables inside your template (for example the location of the user could be a candidate). Instead of writing code to insert it in each view, you could simply write a context processor for it and add it to the TEMPLATE_CONTEXT_PROCESSORS settings in settings.py.

Hope this makes sense. Thanks for taking the class!




回答2:


A context is a variable name -> variable value mapping that is passed to a template.

Context processors let you specify a number of variables that get set in each context automatically – without you having to specify the variables in each render() call.




回答3:


The Context is described quite well in the official documentation. In short:

  1. In day-to-day use, mostly indirectly, because helper functions construct the Context for you

  2. See 1.: you only need it if you use the low-level api

  3. No, a context processor is a function that takes a request and returns a dictionary of variables that are then available in all templates that are rendered with a RequestContext, for example:

    def get_stuff_from_session(request):
        return {'stuff': request.session['stuff']}
    


来源:https://stackoverflow.com/questions/20957388/what-is-a-context-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!