gpt4 book ai didi

django - 如何在 Django 1.8 中动态更改模板路径

转载 作者:行者123 更新时间:2023-12-05 07:52:46 24 4
gpt4 key购买 nike

我想将移动版本添加到我的站点,因此我需要动态更改模板路径以获取移动模板目录或桌面目录。

由于 TEMPLATE_DIRS 自 1.8 版起已弃用,我尝试更改 DjangoTemplates 后端的 DIRS 选项,但没有成功工作。

最佳答案

因为我遇到了同样的挑战,所以我在这里发布了我的代码。我正在使用来自 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()==”mobile“”。

关于django - 如何在 Django 1.8 中动态更改模板路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com