adding settings for extensions and filters #7

Merged
4 commits merged into from Nov 26, 2010
View
@@ -2,6 +2,7 @@
from zope.interface import Interface
from jinja2.loaders import FileSystemLoader
+from jinja2.utils import import_string
from jinja2 import Environment
from pyramid.interfaces import ITemplateRenderer
@@ -12,6 +13,7 @@
class IJinja2Environment(Interface):
pass
+
def asbool(obj):
if isinstance(obj, (str, unicode)):
obj = obj.strip().lower()
@@ -24,6 +26,16 @@ def asbool(obj):
"String is not true/false: %r" % obj)
return bool(obj)
+def parse_filters(filters):
+ if isinstance(filters, basestring):
+ return dict([f.split('=', 1) for f in (f.strip() for f in filters.splitlines()) if f])
+ elif isinstance(filters, list) or isinstance(filters, tuple):
+ return dict(filters)
+ elif isinstance(filters, dict):
+ return filters
+ else:
+ raise ValueError("jinja2.filters is not formated string or list or dict.")
+
def renderer_factory(info):
registry = info.registry
settings = info.settings
@@ -33,6 +45,8 @@ def renderer_factory(info):
directories = settings.get('jinja2.directories')
input_encoding = settings.get('jinja2.input_encoding', 'utf-8')
autoescape = settings.get('jinja2.autoescape', True)
+ extensions = settings.get('jinja2.extensions', '')
+ filters = settings.get('jinja2.filters', '')
if directories is None:
raise ConfigurationError(
'Jinja2 template used without a ``jinja2.directories`` setting')
@@ -41,8 +55,13 @@ def renderer_factory(info):
loader = FileSystemLoader(directories,
encoding=input_encoding)
autoescape = asbool(autoescape)
+ extensions = [e for e in (e.strip() for e in extensions.splitlines()) if e]
+ filters = parse_filters(filters)
environment = Environment(loader=loader, auto_reload=reload_templates,
- autoescape=True)
+ autoescape=True,
+ extensions=extensions)
+ for name, filter in filters.iteritems():
+ environment.filters[name] = import_string(filter) if isinstance(filter, basestring) else filter
registry.registerUtility(environment, IJinja2Environment)
return Jinja2TemplateRenderer(info, environment)
@@ -0,0 +1,7 @@
+from jinja2 import nodes
+from jinja2.ext import Extension
+
+class TestExtension(Extension):
+ tags = set(['test_ext'])
+ def parse(self, parser):
+ return nodes.Const("This is test extension")
@@ -2,6 +2,9 @@
import unittest
+def dummy_filter(value):
+ return 'hoge'
+
class Test_asbool(unittest.TestCase):
def _callFUT(self, value):
from pyramid_jinja2 import asbool
@@ -16,6 +19,31 @@ def test_str_false(self):
def test_str_unrecognized(self):
self.assertRaises(ValueError, self._callFUT, '123')
+class Test_parse_filters(unittest.TestCase):
+ def _callFUT(self, value):
+ from pyramid_jinja2 import parse_filters
+ return parse_filters(value)
+
+ def test_parse_singile_line(self):
+ self.assertEqual(self._callFUT('dummy=dummy'), {'dummy':'dummy'})
+
+ def test_parse_multi_line(self):
+ self.assertEqual(self._callFUT("""\
+ dummy=dummy
+ dummy2=dummy"""),
+ {'dummy':'dummy', 'dummy2':'dummy'})
+
+ def test_parse_list(self):
+ self.assertEqual(self._callFUT(
+ [('dummy', 'dummy'),
+ ('dummy2', 'dummy')]),
+ {'dummy':'dummy', 'dummy2':'dummy'})
+
+ def test_parse_dict(self):
+ self.assertEqual(self._callFUT(
+ {'dummy': 'dummy',
+ 'dummy2': 'dummy'}),
+ {'dummy':'dummy', 'dummy2':'dummy'})
class Base(object):
def setUp(self):
@@ -87,6 +115,62 @@ def test_with_environ(self):
self.assertEqual(renderer.environment, environ)
self.assertEqual(renderer.info, info)
+ def test_with_filters_object(self):
+ from pyramid_jinja2 import IJinja2Environment
+
+ def dummy_filter(value):
+ return 'hoge'
+
+ settings = {'jinja2.directories':self.templates_dir,
+ 'jinja2.filters':{'dummy':dummy_filter}}
+ info = DummyRendererInfo({
+ 'name':'helloworld.jinja2',
+ 'package':None,
+ 'registry':self.config.registry,
+ 'settings':settings,
+ })
+ renderer = self._callFUT(info)
+ environ = self.config.registry.getUtility(IJinja2Environment)
+ self.assertEqual(environ.filters['dummy'], dummy_filter)
+
+ def test_with_filters_string(self):
+ from pyramid_jinja2 import IJinja2Environment
+
+
+ settings = {'jinja2.directories':self.templates_dir,
+ 'jinja2.filters':'dummy=pyramid_jinja2.tests.test_it:dummy_filter'}
+ info = DummyRendererInfo({
+ 'name':'helloworld.jinja2',
+ 'package':None,
+ 'registry':self.config.registry,
+ 'settings':settings,
+ })
+ renderer = self._callFUT(info)
+ environ = self.config.registry.getUtility(IJinja2Environment)
+ self.assertEqual(environ.filters['dummy'], dummy_filter)
+
+ def test_with_extension(self):
+ from pyramid_jinja2 import IJinja2Environment
+ settings = {'jinja2.directories':self.templates_dir,
+ 'jinja2.extensions':"""
+ pyramid_jinja2.tests.extensions.TestExtension
+ """}
+ info = DummyRendererInfo({
+ 'name':'helloworld.jinja2',
+ 'package':None,
+ 'registry':self.config.registry,
+ 'settings':settings,
+ })
+ renderer = self._callFUT(info)
+ environ = self.config.registry.getUtility(IJinja2Environment)
+ self.assertEqual(environ.loader.searchpath, [self.templates_dir])
+ self.assertEqual(renderer.info, info)
+ self.assertEqual(renderer.environment, environ)
+ import pyramid_jinja2.tests.extensions
+ self.assertTrue(isinstance(environ.extensions['pyramid_jinja2.tests.extensions.TestExtension'],
+ pyramid_jinja2.tests.extensions.TestExtension))
+
+
class Jinja2TemplateRendererTests(Base, unittest.TestCase):
def _getTargetClass(self):
from pyramid_jinja2 import Jinja2TemplateRenderer