Permalink
Browse files

add `jinja2.filter` settings variable to register filters to environm…

…ent.
  • Loading branch information...
1 parent 2fb4fe4 commit 2b5eeff9614a6e23de05e778b71a3049ad05487f @aodag aodag committed Nov 25, 2010
Showing with 62 additions and 50 deletions.
  1. +15 −46 pyramid_jinja2/__init__.py
  2. +47 −4 pyramid_jinja2/tests/test_it.py
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,50 +13,6 @@
class IJinja2Environment(Interface):
pass
-class IJinja2FilterRegistry(Interface):
- def register_filter(key, value):
- """ register filter
- """
- def get_filter(key):
- """ get registered filter
- """
-
- def install(environment):
- """ install registered filters to environment
- """
-
-class FilterRegistry(object):
-
- implements(IJinja2FilterRegistry)
-
- def __init__(self):
- self.reg = {}
-
- def register_filter(self, key, value):
- self.reg[key] = value
-
- def get_filter(key):
- return self.reg[key]
-
- def install(self, environment):
- for key, func in self.reg.iteritems():
- environment.filters[key] = func
-
-def _get_filter_registry():
- from pyramid.threadlocal import get_current_registry
- reg = get_current_registry()
- filterreg = reg.queryUtility(IJinja2FilterRegistry)
- if filterreg is None:
- filterreg = FilterRegistry()
- reg.registerUtility(filterreg)
- return filterreg
-
-def register_filter(name, filterfunc):
- filterreg = _get_filter_registry()
- filterreg.register_filter(name, filterfunc)
- return filterfunc
-
-
def asbool(obj):
if isinstance(obj, (str, unicode)):
@@ -69,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
@@ -79,6 +46,7 @@ def renderer_factory(info):
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')
@@ -88,11 +56,12 @@ def renderer_factory(info):
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,
extensions=extensions)
- filterreg = _get_filter_registry()
- filterreg.install(environment)
+ 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)
@@ -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,15 +115,30 @@ def test_with_environ(self):
self.assertEqual(renderer.environment, environ)
self.assertEqual(renderer.info, info)
- def test_with_filter_registry(self):
+ def test_with_filters_object(self):
from pyramid_jinja2 import IJinja2Environment
- from pyramid_jinja2 import register_filter
def dummy_filter(value):
return 'hoge'
- register_filter('dummy', dummy_filter)
- settings = {'jinja2.directories':self.templates_dir}
+ 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,

0 comments on commit 2b5eeff

Please sign in to comment.