Get all templates django detects from TEMPLATE_LOADERS and TEMPLATE_DIRS

限于喜欢 提交于 2020-06-09 12:59:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!