Django模板设置全局变量(默认变量)

  • 发布时间:2017年6月22日 01:27
  • 作者:杨仕航
  • 分类标签: Django
  • 阅读(10954)
  • 评论(1)

有时候,我们需要Templates模板页面可以使用一些变量。这些变量我们在views.py响应时没有返回设置的变量。例如,如下代码:

#coding:utf-8
from django.shortcuts import render

def index(request):
    context = {}
    context['title'] = '测试标题'
    return render(request, 'index.html', context)


上面是某个views.py的方法之一。它将渲染index.html模版(Template)页面,并返回context字典。该字典是传入变量信息给前端页面。对应的index.html如下:

<html>
<head></head>
<body>
    <h3>{{title}}</h3>
    <p>是否登录:{{request.user.is_authenticated}}</p>
</body>
</html>


响应结果除了有title变量值之外,还有是否登录信息。该登录信息来自request变量,问题是上面views.py中返回结果的context中没有写入request变量。而模版也没却有可以获取该变量。

这个当时不是无中生有,我一步一步剖析给大家看。原理讲明白之后,就自然懂得如何设置模版(Templates)的全局变量或者叫默认变量。


render方法是render_to_response方法的简写方式。上面的views.py代码相当于如下:

#coding:utf-8
from django.shortcuts import render_to_response
from django.template import RequestContext

def index(request):
    context = {}
    context['title'] = '测试标题'
    return render_to_response('index.html', context, RequestContext(request))


如果去掉render_to_response的第三个参数,即RequestContext(request)部分。

渲染index.html模版页面就无法得到{{request.user.is_authenticated}}的值,即没有传递request变量给前端页面。很明显RequestContext很关键。

有关RequestContext的内容可以从Django官方文档查得。

该类实例化时会解析settings中的Templates设置中的context_processors配置。新建Django项目settings.py文件中默认的Templates设置如下:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]


大家可发现context_processors有一系列设置,其中根据django.template.context_processors.request的路径找到Django的相关源码。

Django安装在Python的安装目录下Lib/site-packages/目录中,找到django/template/context_processors.py文件,打开可看到request方法:

def request(request):    
    return {'request': request}


该方法返回一个字典,key为request,value为request对象。很明显,render中的request对象就是通过加载settings中的context_processors列表方法得到字典项。

我们也可以采用这种方法,给Django项目设置全局的模版变量。例如,我的Django名称为myproject,在myproject/myproject目录中创建一个contexts.py文件,代码如下:

#coding:utf-8
from django.conf import settings

# 得到语言设置
def lang(request):
    return {'lang': settings.LANGUAGE_CODE}


该文件的方法需要request参数,最后需要返回一个字典即可。

再打开settings.py文件,在Templates中添加刚才写的方法引用:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                
                # 自定义模版全局变量(默认变量)
                'myproject.contexts.lang',
            ],
        },
    },
]


添加模版全局变量之后,我们可以在任意位置渲染模版页面无需再手动写相关代码即可使用该变量。

上一篇:我的网站搭建(第56天) 用户登录注册信息加密

下一篇:Django拆分app为多个小app

评论列表

Money

Money

正好需要这个,真是太巧了,感谢博主

2017-09-19 11:51 回复

新的评论

清空