django-chameleon-templates / djchameleon / loaders / chameleon_tags.py

from chameleon.zpt.template import PageTemplateFile
from django.core.urlresolvers import reverse
from django.utils.importlib import import_module
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from django.utils import six
import ast
import os
import sys

if not six.PY3:
    fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()

MY_ROOT = os.path.normpath(os.path.dirname(__file__))

def url_expr(string):
    # FIXME:  Not really sure why string won't parse correctly in the url_expression function...
    slist = string.split(' ')
    string = slist.pop(0)
    return reverse(string, args=slist)

def url_expression(string):
    def compiler(target, engine):
        the_url = url_expr(string)
        value = ast.Str(the_url)
        return [ast.Assign(targets=[target], value=value)]
    return compiler

def url(view_name, *args, **kwargs):
    return reverse(view_name, args=args, kwargs=kwargs)

djangotags = PageTemplateFile(os.path.join(MY_ROOT, 'defaultmacros', 'djangotags.pt'))

app_macros_dirs = []
for app in settings.INSTALLED_APPS:
    try:
        mod = import_module(app)
    except ImportError as e:
        raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
    macro_dir = os.path.join(os.path.dirname(mod.__file__), 'macros')
    if os.path.isdir(macro_dir):
        if not six.PY3:
            macro_dir = macro_dir.decode(fs_encoding)
        app_macros_dirs.append(macro_dir)

# It won't change, so convert it to a tuple to save memory.
app_macros_dirs = tuple(app_macros_dirs)

class Template(PageTemplateFile):
    expression_types = PageTemplateFile.expression_types.copy()
    expression_types['url'] = url_expression
    def gather_macros(self):
        macro_pt = {}
        for d in app_macros_dirs:
            for pt in os.listdir(d):
                fn = pt.split('.')
                if len(fn) > 1 and fn[-1] == 'pt':
                    macro_pt.update({fn[0]: PageTemplateFile(os.path.join(d, pt))})
        return macro_pt
    def render(self, context):
        context_dict = {'django': djangotags, 'url':url}
        context_dict.update(self.gather_macros())
        for d in context.dicts:
            context_dict.update(d)
        return super(Template, self).render(**context_dict)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.