4👍
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))
16👍
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
2👍
Using Django’s template loaders to return a list of all paths, then pathlib to blob (recursively) down each dir to find all .html
files:
from pathlib import Path
from django import template as django_template
def get_all_templates_files():
dirs = []
for engine in django_template.loader.engines.all():
# Exclude pip installed site package template dirs
dirs.extend(x for x in engine.template_dirs if 'site-packages' not in str(x))
files = []
for dir in dirs:
files.extend(x for x in Path(dir).glob('**/*.html') if x)
return files
- How to serialize queryset in get method in Django Rest Framework?
- Is there a way to set the id value of new Django objects to start at a certain value?
- Learning the Django framework
- Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking i
- Can't git-push to heroku due to "Build stream timed out"