从站点标签加载模板(如果可用)
django-label-templates的Python项目详细描述
用于多站点设置的自定义模板加载程序
这是为多站点案例的django.contrib.sites用户准备的 不同的站点可以有不同的模板,而不仅仅是不同的 造型
自定义模板加载程序将尝试为当前 活动站点,并返回到通用模板。
安装
使用pip安装:
pip install django-label-templates
配置
安装的应用程序
确保django.contrib.sites在INSTALLED_APPS中
指定模板加载程序
您还需要在设置中启用加载程序,类似于django的 缓存的模板加载程序加载程序接受一个iterable(列表或元组) 加载程序来查找模板示例-可能是最常用的-设置:
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',]),],},},]
如果您愿意,这个模板加载程序也可以包装在其他加载程序中, 就像django.template.loaders.cached.Loader
配置站点标签
最后一步,需要一个额外的自定义设置:SITELABELS。
# the import is safe and does NOT depend on django.conf.settingsfromlabel_templates.sitesimportSiteLabels,SiteChoiceclassSITELABELS(SiteLabels):site=SiteChoice('example.com',site_id=1)site2=SiteChoice('example2.com',site_id=2)
此设置用于查找模板的标签前缀。现场 with ID=1将解析为子文件夹site/,以便加载模板 example.html,加载程序将尝试首先查找site/example.html,然后 否则,将尝试只加载example.html。
对于带有ID=2的站点,使用前缀site2。
注意
为了找到匹配的站点,加载程序尝试获取 SiteChoice基于django.contrib.sites.models.Site.name,带有 回退到domain。因此,对于SiteChoice的第一个参数,它是 输入Site.name值最安全
限制
由于{% extends %}标记使用相同的加载程序配置,因此不能 让特定于标签的模板从具有相同 名字
解决方法是以下结构:
templates/ ├── mylabel/ | └── base.html # extends _base.html and overrides stuff ├── _base.html └── base.html # extends _base.html, overrides nothing
支持的版本
这个库是根据django 1.8和1.9测试的。对应的python Django版本的版本适用有关最新信息,请咨询tox.ini。 建立矩阵。