问题
I'm trying to obtain a visual representation of the templates of a Django project, as a hierarchy.
The main idea is to get a list of template names as the default template loading machinery would return (ie honoring TEMPLATE_DIRS, TEMPLATE_LOADERS, etc.) and then parsing the templates looking for {% block %} and {% extends %} tags, in order to create a tree structure. Finally use grapviz for the visualization.
I'm not sure if it's a viable approach. But just to start, how can I load the templates the way I described?
Or maybe, does something similar already exist?
回答1:
Normally, templates are looked up by names online, there is no root entry for every template that might be used.
Thus if you want to grep all used templates in a project, you need to scan every place that loaders in TEMPLATE_LOADERS might check, to generate possible entries for later bottom-to-up checking. This would be hard, some backends of loaders might even does not allow fetch-by-directory operation.
Or you could parse views and urls files inside INSTALLED_APPS to grep template names, but this only works w/ hard-coded name of template and even more difficult.
Also, there might be templates loaded from hard-coded string...
For a given template name, its easier to load the template and check nodes inside it, just as your idea. You could check django.template.base to know how it works.
Furthermore, you could take advantage of django-debug-toolbar to show the templates used for a request. And, IMO, keeping template structure flat, simple and thus determined, is easier to achieve.
来源:https://stackoverflow.com/questions/10149713/django-template-outliner