2024年7月31日水曜日

Django: プロジェクト全体でテンプレートタグを使いたい

以下のような構成とします。

/myproject
/myproject/myproject
/myproject/myapp
/myproject/templates
/myproject/templatetags/__init__.py
/myproject/templatetags/custom_tags.py

settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')], #/myproject/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',
            ],
            'libraries': {
                'custom_tags': 'templatetags.custom_tags', #myproject/myproject以下にしたい場合はmyproject.templatetags.custom_tags とすればよい
            }
        },
    },
]

テンプレートの方で {% load custom_tags %} とすれば、自作テンプレートタグがプロジェクトで共用できるようになる。

0 件のコメント:

コメントを投稿