问题
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))
回答1:
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))
回答2:
In case anyone is still needing this, I'm running 1.9.2 and it looks like
app_template_dirs
is now get_app_template_dirs
and settings.TEMPLATE_DIRS
is now settings.TEMPLATES[0]['DIRS']
Here's what I did:
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))
Then you can iterate through the list as you need using template_list:
for template in template_list:
print template
来源:https://stackoverflow.com/questions/17111822/get-all-templates-django-detects-from-template-loaders-and-template-dirs