Skip to content

Instantly share code, notes, and snippets.

@recamshak
Last active August 29, 2015 13:55
Show Gist options
  • Save recamshak/8701280 to your computer and use it in GitHub Desktop.
Save recamshak/8701280 to your computer and use it in GitHub Desktop.
A Django filter to walk the file system tree. Convenient to include all your angular templates !
import os
import fnmatch
from django import template
register = template.Library()
@register.filter(is_safe=False)
def walk(top_path, glob='*'):
"""
Generate a list of filepath that match the `glob` pattern by walking
the tree top-down starting from `top_path`.
The filepath is relative to `top_path`.
For example to include all the angular templates in "myproject/templates/angular":
{% for filepath in "myproject/templates/angular"|walk:"*.html" %}
<script id="{{ filepath }}" type="text/ng-template">{% include "angular/"|add:filepath %}</script>
{% endfor %}
might render as :
<script id="user/dashboard.tmpl.html" type="text/ng-template">{% include "angular/user/dashboard.tmpl.html" %}</script>
<script id="user/profile/summary.tmpl.html" type="text/ng-template">{% include "angular/user/profile/summary.tmpl.html" %}</script>
<script id="user/profile/edit.tmpl.html" type="text/ng-template">{% include "angular/user/profile/edit.tmpl.html" %}</script>
Notice that `top_path` is relative to the django 'manage.py' path.
"""
for root, dirs, files in os.walk(top_path):
for file in fnmatch.filter(files, glob):
yield os.path.relpath(os.path.join(root, file), top_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment