Django中的上下文是什么? [英] What is a context in Django?

查看:119
本文介绍了Django中的上下文是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个django初学者,所以我想了解上下文和上下文处理器的概念。

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


  • 什么是上下文为什么要使用它?

  • 上下文是否需要在模板中使用才能使用的值?

  • 上下文和上下文处理器是否相同?

我将对您的回应进行深入的分析。感谢提前!

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

推荐答案

当您使用Django模板时,它将被编译一次(仅一次)并存储以备将来使用,作为优化。模板可以在双括号括号中使用变量名称,例如
{{myvar1}},{{myvar2}}。

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 }}, {{ myvar2 }}.

上下文是一个具有变量名称作为键的字典,它们的值作为值。因此,如果上述模板的上下文如下所示:{myvar1:101,myvar2:102},当您将此上下文传递给模板渲染方法时,{{myvar1}}将被替换为101和{{myvar2}},其中102在你的模板这是一个简单的例子,但是真正的Context对象是模板正在呈现的Context。

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.

对于ContextProcessor,这是一个稍微高级的概念。你可以在你的settings.py文件中列出几个Context Processors,它们包含一个HttpRequest对象并返回一个字典(类似于上面的Context对象)。由上下文处理器返回的字典(上下文)被Django合并到您(用户)中传递的上下文中。

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.

上下文处理器的用例是当您总是在模板中插入某些变量(例如,用户的位置可能是候选者)。而不是编写代码以将其插入到每个视图中,您可以简单地为其编写一个上下文处理器,并将其添加到settings.py中的TEMPLATE_CONTEXT_PROCESSORS设置。

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!

-Sid

这篇关于Django中的上下文是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆