Her*_*ntz 5 django django-templates python-2.7
TEMPLATE_DIRS = ('/path/to/templates/',)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
Run Code Online (Sandbox Code Playgroud)
我正在尝试找到一个解决方案,列出我在这些位置(TEMPLATE_DIRS或TEMPLATE_LOADERS)中指定目录的内容.
我需要这样的东西:
template_files = []
for dir in EVERY_DIRECTORY_DJANGO_LOOKS_FOR_TEMPLATES_IN:
template_files.append(os.listdir(dir))
Run Code Online (Sandbox Code Playgroud)
Dou*_*las 12
如果有人仍然需要这个,我正在运行1.9.2,它看起来像是
app_template_dirs现在get_app_template_dirs,settings.TEMPLATE_DIRS现在settings.TEMPLATES[0]['DIRS']
这是我做的:
from django.conf import settings
from django.template.loaders.app_directories import get_app_template_dirs
import os
template_dir_list = []
for template_dir in get_app_template_dirs('templates'):
if settings.ROOT_DIR in template_dir:
template_dir_list.append(template_dir)
template_list = []
for template_dir in (template_dir_list + settings.TEMPLATES[0]['DIRS']):
for base_dir, dirnames, filenames in os.walk(template_dir):
for filename in filenames:
template_list.append(os.path.join(base_dir, filename))
Run Code Online (Sandbox Code Playgroud)
然后,您可以根据需要使用template_list遍历列表:
for template in template_list:
print template
Run Code Online (Sandbox Code Playgroud)
由于模板可以位于基本模板位置下的嵌套目录中,因此我建议使用os.walk来获取所需的模板,它本质上是一个os.listdir将遵循目录的包装器。
django.template.loaders.app_directories.app_template_dirs是所有应用程序模板目录的内部元组,并且TEMPLATE_DIRS是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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3402 次 |
| 最近记录: |