A custom template loader for multi-site set-ups.
This is intended for users of django.contrib.sites
for multi-site cases
where a different site can have different templates, not only a different
styling.
The custom template loaders will try to find a template for the currently active site, and fall back on a generic template.
Install with pip:
pip install django-label-templates
Make sure that django.contrib.sites
is in your INSTALLED_APPS
.
You also need to enable the loader in the settings, similar to Django's cached template loader. The loader takes an iterable (list or tuple) of loaders to find the templates. Example - and probably most used - set-up:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# APP_DIRS must be False if you specify the loaders yourself
'APP_DIRS': False,
'DIRS': [
os.path.join(PROJECT_DIR, 'templates'),
],
'OPTIONS': {
'loaders': [
('label_templates.loaders.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
],
},
},
]
If you wish, this template loader can also be wrapped in other loaders,
like django.template.loaders.cached.Loader
.
For the final step, one extra custom settings is required: SITELABELS
.
# the import is safe and does NOT depend on django.conf.settings
from label_templates.sites import SiteLabels, SiteChoice
class SITELABELS(SiteLabels):
site = SiteChoice('example.com', site_id=1)
site2 = SiteChoice('example2.com', site_id=2)
This settings is used to look up the label-prefix for the templates. The site
with ID=1
will resolve to a subfolder site/
, so to load the template
example.html
, the loader will try to find site/example.html
first, and
failing that, will try to just load example.html
.
For the site with ID=2
, the prefix site2
is used.
Note
To find the matching site, the loader tries to get the label for the
SiteChoice
based on django.contrib.sites.models.Site.name
, with a
fallback to domain
. So, for the first argument of SiteChoice
, it's
safest to enter the Site.name
value.
Since the {% extends %}
tag uses the same loader configuration, you can not
let a label-specific template inherit from a generic template with the same
name.
A workaround is the following structure:
templates/ ├── mylabel/ | └── base.html # extends _base.html and overrides stuff ├── _base.html └── base.html # extends _base.html, overrides nothing
This library is tested against Django 1.8 and 1.9. The corresponding Python
versions for the Django versions apply. Consult tox.ini
for an up to date
build matrix.