从TEMPLATE_LOADERS和TEMPLATE_DIRS获取django检测到的所有模板 [英] Get all templates django detects from TEMPLATE_LOADERS and TEMPLATE_DIRS

查看:100
本文介绍了从TEMPLATE_LOADERS和TEMPLATE_DIRS获取django检测到的所有模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  TEMPLATE_DIRS =('/ path / to / templates /',)

TEMPLATE_LOADERS =(
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',

我正在尝试找到一种解决方案,该解决方案将在这些位置的任何一个位置列出我指定目录的内容( TEMPLATE_DIRS TEMPLATE_LOADERS )。



我需要类似的东西:

  template_files = [] 
表示EVERY_DIRECTORY_DJANGO_LOOKS_FOR_TEMPLATES_IN中的目录:
template_files.append(os.listdir(dir) )


解决方案

由于模板可以位于基础目录下的嵌套目录中模板位置,我建议使用 os.walk 来获取模板您需要,它实际上是 os.li的包装器

django.template.loaders.app_directories.app_template_dirs 是所有应用程序模板目录的内部元组,而 TEMPLATE_DIRS django.template.loaders.filesystem.Loader



以下代码应生成模板目录中所有可用文件的列表(其中可能包括非模板文件):

 从django.conf导入设置
从django.template.loaders.app_directories导入app_template_dirs

导入os

template_files = []
用于(settings.TEMPLATE_DIRS + app_template_dirs)中的template_dir:
用于dir,目录名,os.walk中的文件名(template_dir):
用于文件名中的文件名:
template_files.append(os.path.join(dir,filename))


TEMPLATE_DIRS = ('/path/to/templates/',)

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

I'm trying to find a solution that would list the contents of my specified directory in either of these locations (TEMPLATE_DIRS or TEMPLATE_LOADERS).

I need something like:

template_files = []
for dir in EVERY_DIRECTORY_DJANGO_LOOKS_FOR_TEMPLATES_IN:
    template_files.append(os.listdir(dir))

解决方案

Since templates can be in nested directories under the base template locations I would recommend using os.walk to get the templates you require, it is essentially a wrapper for os.listdir that will follow directories.

django.template.loaders.app_directories.app_template_dirs is an internal tuple of all app template directories and TEMPLATE_DIRS is a setting that is used by django.template.loaders.filesystem.Loader.

The following code should generate a list of all available files in your template directories (this could include non template files):

from django.conf import settings
from django.template.loaders.app_directories import app_template_dirs

import os

template_files = []
for template_dir in (settings.TEMPLATE_DIRS + app_template_dirs):
    for dir, dirnames, filenames in os.walk(template_dir):
        for filename in filenames:
            template_files.append(os.path.join(dir, filename))

这篇关于从TEMPLATE_LOADERS和TEMPLATE_DIRS获取django检测到的所有模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆