Permalink
Browse files

Merge pull request #108 from andreif/add-jinja2-extension

added jinja2 extension
  • Loading branch information...
Barry Coughlan
Barry Coughlan committed Nov 16, 2012
2 parents 451beb1 + a205faa commit 39c1d475dddcf324954345ddca5458166d69aa82
Showing with 37 additions and 0 deletions.
  1. +37 −0 hamlpy/ext.py
View
@@ -0,0 +1,37 @@
+# coding=utf-8
+import jinja2.ext
+import hamlpy
+import os
+
+HAML_FILE_NAME_EXTENSIONS = ['haml', 'hamlpy']
+
+
+def clean_extension(file_ext):
+ if not isinstance(file_ext, basestring):
+ raise Exception('Wrong file extension format: %r' % file_ext)
+ if len(file_ext) > 1 and file_ext.startswith('.'):
+ file_ext = file_ext[1:]
+ return file_ext.lower().strip()
+
+
+def get_file_extension(file_path):
+ file_ext = os.path.splitext(file_path)[1]
+ return clean_extension(file_ext)
+
+
+def has_any_extension(file_path, extensions):
+ file_ext = get_file_extension(file_path)
+ return file_ext and extensions and [clean_extension(e) for e in extensions]
+
+
+class HamlPyExtension(jinja2.ext.Extension):
+
+ def preprocess(self, source, name, filename=None):
+ if name and has_any_extension(name, HAML_FILE_NAME_EXTENSIONS):
+ compiler = hamlpy.Compiler()
+ try:
+ return compiler.process(source)
+ except Exception as e:
+ raise jinja2.TemplateSyntaxError(e, 1, name=name, filename=filename)
+ else:
+ return source

0 comments on commit 39c1d47

Please sign in to comment.