この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:2
更新日時:2019-05-27 22:57:46
タイトル: テンプレートで定数を使用する方法
SEOタイトル: 【django】テンプレートで定数を使用する方法
| この記事の要点 |
- Django テンプレート内で共通定数を使う方法
settings.py と同階層に const.py を作り、コンテキストプロセッサとして定数を返す関数を定義
settings.py の TEMPLATES → context_processors に登録
- テンプレートで
{{ CONST_1 }} のように変数名そのままで参照できる
|
setting.pyと同階層にconst.pyを作成する。
|
def consts(request):
return {
'CONST_1': 'test1',
'CONST_2': 'test2',
}
|
setting.pyのcontext_processorsに上記のファイルを追加する。
|
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'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',
'app1.const.consts',
],
},
},
]
|
※app1の部分はプロジェクト名に変更
適当なテンプレートで定数を出力させる。
|
<h1>テスト</h1>
{{ CONST_1 }}
{{ CONST_2 }}
|