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

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

由于 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“”。

https://stackoverflow.com/questions/33281269/

相关文章:

c# - 在 WPF 应用程序中单击按钮会重置文化

jakarta-ee - 缺少 [类(class)] 的类(class)详细信息。为 [class]

python - 标准Django/python单位转换包

python - AssertListEqual 不改变类 __eq__ 方法

android - ViewPager setCurrentItem 不流畅

c# - 将可为空的 int 映射到可为空的 int + automapper

java - 带有 GIT 命令的 ProcessBuilder 没有给出结果

python - 无法使用 OS X El Capitan pip 安装任何东西

python - Pytest 在使用预定义参数 vai argparse 运行测试时抛出参数错误

linux-kernel - Linux 内核模块在卸载期间挂起