Commits

Jacob Smullyan committed 0cbc262

initial commit

  • Participants

Comments (0)

Files changed (6)

+.*\.pyc
+
+README
+setup.py
+./djmako/__init__.py
+./djmako/loader.py
+Mako templates for django >= 1.2.
+
+Portions of this code are taken from django-smorgasbord's mako
+support.  Smorgasbord provided a monkeypatch to facilitate the use of
+other templating languages within django 1.1; with django 1.2, this
+monkeypatch is no longer necessary, and there is no longer any
+particular reason to conjoin template loaders for different languages
+in one project.
+
+To use, add `'djmako.MakoLoader'` to `settings.TEMPLATE_LOADERS`, and
+define settings.MAKO_TEMPLATE_DIRS (a tuple of directories in which to
+look for mako templates -- required) and `settings.MAKO_TEMPLATE_OPTS`
+(a dictionary of other parameters to pass to Mako's `TemplateLookup`
+class -- optional).
+
+For instance, in `settings.py` you might have::
+
+  TEMPLATE_LOADERS = (
+     'djmako.MakoLoader',
+     'django.template.loaders.filesystem.Loader',
+     'django.template.loaders.app_directories.Loader',
+  )
+
+  MAKO_TEMPLATE_DIRS=(os.path.join(PROJECT_ROOT, 'templates', 'mako'),)
+
+  MAKO_TEMPLATE_OPTS=dict(input_encoding='utf-8',
+                          module_directory=os.path.join(
+      tempfile.gettempdir(),
+      os.environ.get('LOGNAME', 'someuser'),
+      'mysite',
+      PROJECT_ROOT.split('/')[-2]))
+
+Note that in the above configuration, the mako loader is checked
+first, and django templates afterwards.
+
+License
+=======
+
+Copyright (c) 2010 Jacob Smullyan
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the
+   distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+

File djmako/__init__.py

+"""
+Mako templates for django >= 1.2.
+"""
+
+from .loader import MakoLoader

File djmako/loader.py

+"""
+Mako templates for django >= 1.2.
+"""
+
+from django.conf import settings
+from django.template import TemplateDoesNotExist
+from django.template.context import Context
+from django.template.loaders.filesystem import Loader as FSLoader
+
+from mako.exceptions import MakoException, TopLevelLookupException
+from mako.template import Template
+from mako.lookup import TemplateLookup
+
+
+def context_to_dict(ctxt):
+    res = {}
+    for d in reversed(ctxt.dicts):
+        # sometimes contexts will be nested
+        if isinstance(d, Context):
+            res.update(context_to_dict(d))
+        else:
+            res.update(d)
+    return res
+
+
+def _get_start_and_end(source, lineno, pos):
+    start = 0
+    for n, line in enumerate(source.splitlines()):
+        if n == lineno:
+            start += pos
+            break
+        else:
+            start += len(line) - 1
+    return start, start
+
+
+class MakoExceptionWrapper(Exception):
+    def __init__(self, exc, origin):
+        self._exc = exc
+        self._origin = origin
+        self.args = self._exc.args
+
+    def __getattr__(self, name):
+        return getattr(self._exc, name)
+
+    @property
+    def source(self):
+        return (self._origin,
+                _get_start_and_end(self._exc.source,
+                                   self._exc.lineno,
+                                   self._exc.pos))
+
+
+class MakoTemplate(object):
+    def __init__(self, template_obj, origin=None):
+        self.template_obj = template_obj
+        self.origin = origin
+
+    def render(self, context):
+        try:
+            return self.template_obj.render_unicode(**context_to_dict(context))
+        except MakoException, me:
+            if hasattr(me, 'source'):
+                raise MakoExceptionWrapper(me, self.origin)
+            else:
+                raise me
+
+_lookup = None
+
+
+def get_lookup():
+    global _lookup
+    if _lookup is None:
+        opts = getattr(settings, 'MAKO_TEMPLATE_OPTS', {})
+        _lookup = TemplateLookup(directories=settings.MAKO_TEMPLATE_DIRS,
+                                 **opts)
+    return _lookup
+
+
+class MakoLoader(FSLoader):
+    is_usable = True
+
+    def load_template(self, template_name, template_dirs=None):
+        lookup = get_lookup()
+        try:
+            real_template = lookup.get_template(template_name)
+            return MakoTemplate(real_template, template_name), template_name
+        except TopLevelLookupException:
+            raise TemplateDoesNotExist(
+                'mako template not found for name %s' % template_name)
+        except MakoException, me:
+            if hasattr(me, 'source'):
+                raise MakoExceptionWrapper(me, origin)
+            raise me
+from distutils.core import setup
+from os import path 
+
+description="mako template support for Django 1.2"
+
+fp = open(path.join(path.dirname(path.realpath(__file__)), 'README'))
+long_description = fp.read()
+
+VERSION='0.1'
+
+setup(author="Jacob Smullyan",
+      author_email='smulloni@smullyan.org',
+      description=description,
+      long_description=long_description,
+      license="BSD",
+      platforms='OS Independent',
+      name="djmako",
+      url="http://code.google.com/p/smorgasbord/",
+      classifiers=["Development Status :: 3 - Alpha",
+                   "Environment :: Web Environment",
+                   "Framework :: Django",
+                   "Intended Audience :: Developers",
+                   "License :: OSI Approved :: BSD License",
+                   "Operating System :: OS Independent",
+                   "Programming Language :: Python",
+                   'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
+                   'Topic :: Software Development :: Libraries :: Python Modules',
+                   'Topic :: Text Processing :: Markup :: HTML',
+      ],
+      version=VERSION,
+      keywords="django mako templating",
+      packages=("djmako",),
+      package_dir={'': "."},
+      )