我想将移动版本添加到我的站点,所以我需要动态更改模板路径,以获得移动模板目录或桌面目录。
由于TEMPLATE_DIRS从1.8版开始就被弃用了,我试图更改DjangoTemplates后端的DIRS选项,但它不起作用。
发布于 2015-10-30 00:12:51
因为我遇到了同样的挑战,所以我在这里发布了我的代码。我使用来自django_mobile的get_flavor来检测要显示的内容,并且我想使用django_admin_bootstrapped的标准管理目录(已安装)和常规的django管理。此外,我只想用管理页面干扰加载器,而不是常规页面--在后者的情况下,加载器什么也不做。
所以这对我来说很有效:
import os.path
from django.template.loaders.base import Loader
from django.template.loader import LoaderOrigin
from django.template import TemplateDoesNotExist
from django_mobile import get_flavour
class Myloader(Loader):
is_usable = True #this line is necessary to make it work
def load_template_source(self, template_name, template_dirs=None):
path_split = template_name.split("/")
if not u'admin' in path_split:
raise TemplateDoesNotExist
template_short_name = path_split[-1]
if get_flavour() == "mobile":
basepath = r'/path/to/django_admin_bootstrapped/templates/admin'
path = os.path.join(basepath,template_short_name)
else:
basepath = r'/path/to/django/contrib/admin/templates/admin'
path = os.path.join(basepath,template_short_name)
try:
with open(path,"r") as f1:
template_string = f1.read()
except IOError:
raise TemplateDoesNotExist
template_origin = LoaderOrigin(template_short_name, self.load_template_source, template_name, template_dirs)
return (template_string, template_origin)如果你想通过一些不同的东西来区分模板路径,比如url中的名字,你需要通过查找inntemplate_name来替换"if get_flavour()==“移动”“。
https://stackoverflow.com/questions/33281269
复制相似问题