从TEMPLATE_LOADERS和TEMPLATE_DIRS获取django检测到的所有模板 [英] Get all templates django detects from TEMPLATE_LOADERS and TEMPLATE_DIRS
问题描述
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 来获取模板您需要,它实际上是 以下代码应生成模板目录中所有可用文件的列表(其中可能包括非模板文件): I'm trying to find a solution that would list the contents of my specified directory in either of these locations ( I need something like:
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 The following code should generate a list of all available files in your template directories (this could include non template files):
这篇关于从TEMPLATE_LOADERS和TEMPLATE_DIRS获取django检测到的所有模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! os.li的包装器
django.template.loaders.app_directories.app_template_dirs
是所有应用程序模板目录的内部元组,而 TEMPLATE_DIRS
是 django.template.loaders.filesystem.Loader $ c使用的设置$ c>。
从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',
)
TEMPLATE_DIRS
or TEMPLATE_LOADERS
).template_files = []
for dir in EVERY_DIRECTORY_DJANGO_LOOKS_FOR_TEMPLATES_IN:
template_files.append(os.listdir(dir))
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
.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))