Настроить загрузку мультисайтовых шаблонов - PullRequest
2 голосов
/ 01 октября 2019

Текущий макет templates:

Вскоре будет создан второй сайт, на different domain. Логика обоих сайтов одинакова. Названия шаблонов одинаковы. Необходимо, чтобы при входе из first domain его шаблоны загружались при входе из second domain - его шаблонов. Если таких шаблонов нет, загрузите какой-нибудь общий шаблон. Делать копии шаблонов не нужно.

apps
    app1
        templates
            folder_with_templates_1
                index.html
            admin
                index.html
    app2
        templates
            folder_with_templates_2
                index.html
            admin
                index.html
    templates
        admin
            index.html
        404.html
        500.html

Какие варианты безболезненного решения?

  1. Напишите какой-нибудь костыль template loader? Ничего не вышло. Я могу при необходимости выложить код.

  2. Костыль Middleware, который определит сайт и загрузит соответствующие шаблоны?

  3. Настроить dirs in the settings каждого сайта?

  4. Найден Django-multisite, но не удалось его настроить. При необходимости я покажу свои настройки. https://github.com/ecometrica/django-multisite

Настройки первого сайта:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '..', 'apps', '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',
                # Project context processors
                'apps.landing.context_processors.landing_settings',
                'apps.landing.context_processors.page404_context',
                'apps.landing.context_processors.user_token_data',
            ],
        },
    },
]

1 Ответ

2 голосов
/ 01 октября 2019

иерархия шаблонов

apps
  app1
    templates
      site1
        app1
          index.html
      site2
        app1
          index.html
  app2
    templates
      site1
        app2
          index.html
      site2
        app2
          index.html
  ...
  templates
    index.html
    ...

настройки

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '..', 'apps', 'templates')],
        # 'APP_DIRS': True,
        'OPTIONS': {
            'loaders': ['apps.loaders.Loader', 'django.template.loaders.app_directories.Loader',],
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # Project context processors
                'apps.landing.context_processors.landing_settings',
                'apps.landing.context_processors.page404_context',
                'apps.landing.context_processors.user_token_data',
            ],
        },
    },
]

загрузчики

class Loader(FilesystemLoader):
    def get_path_dirs(self, template_path):
        return get_app_template_dirs(template_path)

    def get_template_sources(self, *args, **kwargs):
        start = args[0]

        template_path = 'templates/site_{}/'.format(Site.objects.get_current().id)

        for i in args[0].split('/'):
            if '.' in i:
                x = i
            else:
                template_path += i + '/'
        if self.get_path_dirs(template_path):
            template_name = self.get_path_dirs(template_path)[0] + x
        else:
            template_name = ''
            if Site.objects.get_current().id != 1:
                template_path = 'templates/site_1/'.format(Site.objects.get_current().id)

                for i in args[0].split('/'):
                    if '.' in i:
                        x = i
                    else:
                        template_path += i + '/'
                if self.get_path_dirs(template_path):
                    template_name = self.get_path_dirs(template_path)[0] + x
                else:
                    apps_folder = os.path.dirname(os.path.abspath(__file__)) + '/templates/' + x
                    if os.path.exists(apps_folder):
                        apps_folder = os.path.dirname(os.path.abspath(__file__)) + '/templates/' + x
                        template_name = os.path.exists(apps_folder)

        if django_version < (2, 0, 0):
            args = [template_name, None]
        else:
            args = [template_name]
        if args[0] != '':
            yield Origin(
                name=args[0],
                template_name=start,
                loader=self,
            )
...