Permalink
Browse files

Djinja now supports adding extensions and filters 'automatically'

  • Loading branch information...
Syrus Akbary
Syrus Akbary committed Jun 9, 2011
1 parent 23d9ccb commit f69630344ad49ab1e63fdade4c0dd8a6c4b81291
View
@@ -5,18 +5,12 @@ Djinja
Djinja tries to **integrate Jinja2 in Django**. The aim is to replace
completely the Django's template system, **including administration**.
-Also, **Djinja can render HAML pages**, and is as just **simple** as put the
-**.haml extension** to your template. *Requires HamlPy*
-
Currently, the following templating modules have been written and are working:
- Django administration
- Django Debug Toolbar
-Furthermore, is planned to implement one Django management command (**NOT CURRENTLY**):
-
-- `compiletemplates`: Compile the Jinja2 templates for completely fast views in your website.
-
+In a near future, you could convert **Django templates syntax to Jinja2 syntax**, isn't awesome?
If you have ideas please let us know.
@@ -40,30 +34,59 @@ Installation
**IMPORTANT**: You have to adapt your website templates to Jinja2 or you
-will get an error when rendering.
+will get an error when rendering (until the djinja converser is ready).
+
+Custom filters and extensions
+=============================
+
+Djinja uses the same templatetag library approach as Django, meaning
+your app has a ``templatetags`` directory, and each of it's modules
+represents a "template library", providing new filters and tags.
+
+A custom ``Library`` class in ``djinja.template.Library`` can be used
+to register Jinja-specific components.
+
+Djinja can automatically make your existing Django filters usable in
+Jinja, but not your custom tags - you need to rewrite those as Jinja
+extensions manually.
+
+Example for a Jinja-enabled template library::
+
+ from djinja import template
+ register = template.Library()
-Configuration
-=============
+ register.filter(plenk, 'plenk') # Filter function
+ register.extension(FooExtension) # Jinja version of the tag
+ register.tag(my_function_name) # A global function/object
+ register.set(a='hello') # A context variable (named a)
-No configuration for now, but is expected in next releases.
+You may also define additional extensions, filters, tests, and globas via your ``settings.py``::
+ JINJA2_FILTERS = (
+ 'path.to.myfilter',
+ )
+ JINJA2_EXTENSIONS = (
+ 'jinja2.ext.do',
+ )
HAML
====
-If you have installed HamlPy (https://github.com/jessemiller/HamlPy),
-you can render any HAML-page (\*.haml) without any additional configuration.
+Djinja can render HAML pages (having installed ``HamlPy`` - https://github.com/jessemiller/HamlPy), and is as just simple as put the .haml extension to your template and adding ``'djinja.template.extensions.haml'`` in the JINJA2_EXTENSIONS variable of your settings::
+
+
+ JINJA2_EXTENSIONS = (
+ ...
+ 'djinja.template.extensions.haml',
+ ...
+ )
**HAML templates can also include,extend,etc HTML templates and viceversa.**
Administration
==============
-For install the Django administration Jinja2 templating just add
-
- ``'djinja.contrib.admin',``
-
-before 'django.contrib.admin' in your INSTALLED_APPS in `settings.py`.
+For install the Django administration Jinja2 templating just add ``'djinja.contrib.admin',`` before 'django.contrib.admin' in your INSTALLED_APPS in `settings.py`.
Example configuration::
@@ -79,8 +102,8 @@ Benchmarking
------------
Running tests::
-
- ab -n100 http://localhost/admin/
+
+ ab -n100 http://localhost/admin/
In Django
@@ -98,11 +121,7 @@ With Jinja2 (Djinja)
Django Debug Toolbar
====================
-For install the Django Debug Toolbar Jinja2 templating just add
-
- ``'djinja.contrib.debug_toolbar',``
-
-before 'debug_toolbar' in your INSTALLED_APPS in `settings.py`.
+For install the Django Debug Toolbar Jinja2 templating just add ``'djinja.contrib.debug_toolbar',`` before 'debug_toolbar' in your INSTALLED_APPS in `settings.py`.
Example configuration::
View
@@ -13,7 +13,8 @@
#Taked majoritarily from Coffin's <http://www.github.com/dcramer/coffin> __init__.py
__all__ = ('__version__', '__build__', '__docformat__', 'get_revision')
-__version__ = (0, 5, 5)
+__version__ = (0, 6)
+__author__ = 'Syrus Akbary Nieto'
__docformat__ = 'restructuredtext en'
import os
@@ -95,64 +95,3 @@ def parse(self, parser):
register.extension(LoadExtension)
-
-
-class HamlishExtension(Extension):
-
- def __init__(self, environment):
- super(HamlishExtension, self).__init__(environment)
-
- environment.extend(
- hamlish_mode='compact',
- hamlish_file_extensions=('.haml',),
- hamlish_indent_string=' ',
- hamlish_newline_string='\n',
- hamlish_debug=False,
- hamlish_enable_div_shortcut=False,
- )
-
-
- def preprocess(self, source, name, filename=None):
- import os
- if not os.path.splitext(name)[1] in \
- self.environment.hamlish_file_extensions:
- return source
- from extended import haml
- c = haml.Compiler()
- return c.process(source)
-
-try:
- from hamlpy import hamlpy
-except:
- pass
-else:
- register.extension(HamlishExtension)
-
-
-try:
- from mediagenerator.contrib.jinja2ext import MediaExtension
- register.extension(MediaExtension)
-except:
- pass
-
-# h = self.get_preprocessor(self.environment.hamlish_mode)
-# try:
-# return h.convert_source(source)
-# except TemplateIndentationError, e:
-# raise TemplateSyntaxError(e.message, e.lineno, name=name, filename=filename)
-# except TemplateSyntaxError, e:
-# raise TemplateSyntaxError(e.message, e.lineno, name=name, filename=filename)
-
-
-# def get_preprocessor(self, mode):
-#
-# if mode == 'compact':
-# output = Output(indent_string='', newline_string='')
-# elif mode == 'debug':
-# output = Output(indent_string=' ', newline_string='\n')
-# else:
-# output = Output(indent_string=self.environment.hamlish_indent_string,
-# newline_string=self.environment.hamlish_newline_string)
-#
-# return Hamlish(output, mode == 'debug',
-# self.environment.hamlish_enable_div_shortcut)
@@ -28,7 +28,8 @@ def url(view_name, *args, **kwargs):
raise
return url
-
+
+
@register.filter
def timesince(value, *arg):
if value is None or isinstance(value, Undefined):
@@ -98,20 +99,49 @@ def firstof(vars):
return var
return ''
+from django.utils.safestring import SafeUnicode, SafeData, EscapeData
+from jinja2 import Markup, environmentfilter
+
+#Taked from coffin.interop https://github.com/cdleary/coffin/blob/master/coffin/interop.py
+def django_filter_to_jinja2(filter_func):
+ def _convert(v):
+ if isinstance(v, SafeData):
+ return Markup(v)
+ if isinstance(v, EscapeData):
+ return Markup.escape(v) # not 100% equivalent, see mod docs
+ return v
+ def conversion_wrapper(*args, **kwargs):
+ result = filter_func(*args, **kwargs)
+ return _convert(result)
+ if hasattr(filter_func, 'needs_autoescape'):
+ @environmentfilter
+ def autoescape_wrapper(environment, *args, **kwargs):
+ kwargs['autoescape'] = environment.autoescape
+ return conversion_wrapper(*args, **kwargs)
+ return autoescape_wrapper
+ else:
+ return conversion_wrapper
+
+
@register.filter
def floatformat(value, arg=-1):
"""Builds on top of Django's own version, but adds strict error
checking, staying with the philosophy.
"""
from django.template.defaultfilters import floatformat
- from coffin.interop import django_filter_to_jinja2
arg = int(arg) # raise exception
result = django_filter_to_jinja2(floatformat)(value, arg)
if result == '': # django couldn't handle the value
raise ValueError(value)
return result
-
+
+@register.filter
+def jsencode (value):
+ import urllib
+ value = 'document.write("%s")' % value
+ encoded = urllib.quote(unicode(value).encode('utf-8'))
+ return '<script>eval(decodeURIComponent("%s"));</script>'% encoded
from djinja.template.base import import_library
django_filters = import_library('django.template.defaultfilters').filters
for filter in django_filters.keys():
- register.filter(django_filters[filter])
+ register.filter(django_filter_to_jinja2(django_filters[filter]))
@@ -0,0 +1,23 @@
+from jinja2.ext import Extension
+class haml(Extension):
+ def __init__(self, environment):
+ super(haml, self).__init__(environment)
+
+ environment.extend(
+ hamlish_mode='compact',
+ hamlish_file_extensions=('.haml',),
+ hamlish_indent_string=' ',
+ hamlish_newline_string='\n',
+ hamlish_debug=False,
+ hamlish_enable_div_shortcut=False,
+ )
+
+
+ def preprocess(self, source, name, filename=None):
+ import os
+ if not os.path.splitext(name)[1] in \
+ self.environment.hamlish_file_extensions:
+ return source
+ from extended import haml as _haml
+ c = _haml.Compiler()
+ return c.process(source)
View
@@ -1,7 +1,7 @@
from django.template.base import *
from django.template.defaulttags import *
-from django.template.loader_tags import *
from django.templatetags.i18n import TranslateNode, BlockTranslateNode
+from django.template.loader_tags import ExtendsNode,IncludeNode,ConstantIncludeNode,BlockNode
#l = Library()
#l.simple_tag(lambda x:x)
View
@@ -3,10 +3,10 @@
setup(
name='Djinja',
version=".".join(map(str, __import__("djinja").__version__)),
- description='Easy Jinja2 templates integration in Django (including admin), with HAML syntax support.',
+ description='A package that makes possible the integration of Jinja2 in Django, in a clean way.',
long_description=open('README.rst').read(),
author='Syrus Akbary Nieto',
- author_email='dimension.net@gmail.com',
+ author_email='me@syrusakbary.com',
url='http://github.com/syrusakbary/djinja',
license='BSD',
packages=find_packages(exclude=['ez_setup']),
Oops, something went wrong.

0 comments on commit f696303

Please sign in to comment.