django中将settings中全局变量应用于模板templates中

以项目名dispy为例,把站点名变量应用于模板中

⑴ 在项目目录下创建dispy/global_settings.py文件

from django.conf import settings


def get_global_settings(request):
    context = {
        ‘site_name‘: settings.SITE_NAME,
        ‘site_short_name‘: settings.SITE_SHORT_NAME,
    }
    return context

⑵ 在setting.py中templates加入get_global_settings方法

TEMPLATES = [
    {
        ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
        ‘DIRS‘: [os.path.join(BASE_DIR, ‘themes‘, THEME, ‘templates‘)],
        ‘APP_DIRS‘: True,
        ‘OPTIONS‘: {
            ‘context_processors‘: [
                ‘dispy.global_settings.get_global_settings‘,
                ‘django.template.context_processors.debug‘,
                ‘django.template.context_processors.request‘,
                ‘django.contrib.auth.context_processors.auth‘,
                ‘django.contrib.messages.context_processors.messages‘,
            ],
        },
    },
]

⑶ templates中引用

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{{ page_name }} - {{ site_short_name }}</title>

相关推荐