首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Django 1.8中动态更改模板路径

问如何在Django 1.8中动态更改模板路径
EN

Stack Overflow用户
提问于 2015-10-22 20:39:19
回答 1查看 813关注 0票数 3

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

由于TEMPLATE_DIRS从1.8版开始就被弃用了,我试图更改DjangoTemplates后端的DIRS选项,但它不起作用。

EN

回答 1

Stack Overflow用户

发布于 2015-10-30 00:12:51

因为我遇到了同样的挑战,所以我在这里发布了我的代码。我使用来自django_mobile的get_flavor来检测要显示的内容,并且我想使用django_admin_bootstrapped的标准管理目录(已安装)和常规的django管理。此外,我只想用管理页面干扰加载器,而不是常规页面--在后者的情况下,加载器什么也不做。

所以这对我来说很有效:

代码语言:javascript
复制
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()==“移动”“。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33281269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档