- Author:
- wonderbeyond
- Posted:
- September 28, 2015
- Language:
- Python
- Version:
- Not specified
- Score:
- 0 (after 0 ratings)
list django template's inheritance hierarchy
Example:
DJANGO_SETTINGS_MODULE=mysite.settings django-templates-tree.py base.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #!/usr/bin/env python
import os
import re
import sys
import json
import itertools
import collections
def list_templates():
from django.template.loaders.app_directories import app_template_dirs
res = []
for dirpath, dirs, fnames in itertools.chain(*(os.walk(path) for path in app_template_dirs)):
for fname in fnames:
if os.path.splitext(fname)[1] == '.html' and 'templates' in dirpath:
filepath = os.path.join(dirpath, fname)
res.append(os.path.join(filepath))
return res
def search_file(filepath, regex):
if filepath in exhausted_templates:
return None
with open(filepath) as f:
for l in f:
res = regex.search(l)
if res:
exhausted_templates.append(filepath)
return res
return None
def find_children(path, template_name):
reg = re.compile(
r"""\{\%%\s*extends\s+[\'\"]%s[\'\"]\s*\%%\}""" % template_name)
res = []
for filepath in templates:
if search_file(filepath, reg):
res.append(os.path.join(filepath))
return res
def Tree():
return collections.defaultdict(Tree)
if __name__ == '__main__':
if len(sys.argv) < 2:
print '''Example:
DJANGO_SETTINGS_MODULE=mysite.settings %s base.html
''' % sys.argv[0]
sys.exit(1)
templates = list_templates()
exhausted_templates = []
tree = Tree()
template_reg = re.compile(r'^.*?/templates/')
def fulfill(tree, template_name):
template_name = template_reg.sub('', template_name)
sub_tree = tree[template_name]
for fname in find_children('.', template_name):
fulfill(sub_tree, fname)
top = sys.argv[1]
fulfill(tree, top)
print(json.dumps(tree, indent=4))
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.