首页 > 解决方案 > 基于域加载模板

问题描述

有两个具有不同域 ( first_example.com, second_example.com) 的站点。他们有一个共同的数据库和共同的逻辑。该任务是需要完成的,以便为每个站点加载其自己的模板。

比如会有一个文件结构

__landing
____templates
______landing
________site_1
__________ index.html
________site_2
__________ index.html

有必要在打开时加载first domain模板。site_1并且在打开second domain, 模板时site_2已加载。

我想我需要以某种方式写template_loader,但我还不明白该怎么做。

标签: djangodjango-templates

解决方案


不是在模板目录结构中嵌套“每个站点”模板,而是使用两个不同的根模板目录,即,而不是

/templates
   /app-one
      site1/
        index.html
      site2/
        index.html

你要:

/site1-templates
   /app-one
      index.html
/site2-templates
   /app-one
      index.html

然后在每个设置文件中(您对每个站点都有不同的设置吗?),只需指定正确的路径TEMPLATES.DIRS

# site1 settings

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        os.path.join(PROJECT_ROOT, 'site1-templates'),
    ],
    'OPTIONS': {
    # etc
    }
 }]

注意:如果您需要保留一些常用模板,可以将它们放在第三个目录(即)中basetemplates并将其添加到.TEMPLATES.DIRS

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        os.path.join(PROJECT_ROOT, 'site1-templates'),
        os.path.join(PROJECT_ROOT, 'base-templates'),
    ],
    'OPTIONS': {
    # etc
    }
 }]

推荐阅读