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

查看:42
本文介绍了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 }} and {{ myvar2 }}.

A Context 是一本字典变量名作为,它们的值作为.因此,如果上述模板的上下文看起来像:{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 文件中列出一些上下文处理器,它们接收一个 HttpRequest 对象并返回一个字典(类似于上面的 Context 对象).由 Context Processor 返回的字典(上下文)被 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!

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

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