- Python 100%
| .zed | ||
| django_project | ||
| django_templates | ||
| doc | ||
| .gitignore | ||
| LICENSE | ||
| manage.py | ||
| poetry.lock | ||
| pyproject.toml | ||
| README.md | ||
django-templates
django-templates is a Django app that provides a centralized registry for accessing the dictionary of templates used in a request. It also provides a context processor for accessing the registry.
Installation
Add django_templates to the list of INSTALLED_APPS in your project's settings.py.
INSTALLED_APPS = [
...
django_templates,
...
]
Add the templates context processor to your project's settings.py.
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
...
# Optionally add the global templates directory if it is not in an app's templates directory.
"DIRS": [
"path/to/global/templates",
],
...
# Add the templates context processor to the list of context processors.
"OPTIONS": {
"context_processors": [
...
"django_templates.context_processors.templates",
...
],
},
},
]
Then you can use the DJANGO_TEMPLATES setting in settings.py to override the templates of apps using this library.
DJANGO_TEMPLATES = {
"app_name/index": "templates_dir/my_templates/index.html"
}
Usage
To use the template registry in your app, create the file "your_app/django_templates.py" and define your templates there.
First the DJANGO_TEMPLATES variable, which should contain your default template dictionary. Then these templates are overridden by
a function called get_django_templates that returns a dictionary of templates.
DJANGO_TEMPLATES = {
"app_name/index": "app_name/templates/app_name/index.html"
...
}
def get_django_templates(css_provider: str) -> dict:
if css_provider == "bootstrap5":
return MY_BOOTSTRAP5_TEMPLATES
elif css_provider == "tailwindcss":
return MY_TAILWINDCSS_TEMPLATES
return MY_DEFAULT_TEMPLATES
Accessing the registry in your templates
{% load templates %}
{{ "template_name"|template }}
Accessing the registry un your views
from django_templates.utils import django_template
def my_view(request):
template = django_template("template_name")
...
Accessing the registry directly
from django.conf import settings
my_template = settings.DJANGO_TEMPLATES['my_app/my_template']