我认为最佳做法 Django 已经给我们演示了.
即通过配置模板的 context_processors.
比如 Django 默认模板配置的如下 :
```python
#
https://docs.djangoproject.com/en/dev/ref/settings/#templatesTEMPLATES = [
{
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"
django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
},
},
```
这些 processor 其实就是一个函数 .返回你需要的对象即可.
比如 messages 这个的实现如下:
```python
from django.contrib.messages.api import get_messages
from django.contrib.messages.constants import DEFAULT_LEVELS
def messages(request):
"""
Return a lazy 'messages' context variable as well as
'DEFAULT_MESSAGE_LEVELS'.
"""
return {
'messages': get_messages(request),
'DEFAULT_MESSAGE_LEVELS': DEFAULT_LEVELS,
}
```