Permalink
Browse files

Added extension ordering, this fixes #376.

--HG--
branch : trunk
  • Loading branch information...
1 parent 4855908 commit 5b3f4dcca20184f9edad5e47fee35b25d5c2a5be @mitsuhiko mitsuhiko committed Apr 12, 2010
Showing with 25 additions and 3 deletions.
  1. +7 −2 jinja2/environment.py
  2. +7 −0 jinja2/ext.py
  3. +1 −1 jinja2/parser.py
  4. +10 −0 jinja2/testsuite/ext.py
View
@@ -334,6 +334,11 @@ def overlay(self, block_start_string=missing, block_end_string=missing,
lexer = property(get_lexer, doc="The lexer for this environment.")
+ def iter_extensions(self):
+ """Iterates over the extensions by priority."""
+ return iter(sorted(self.extensions.values(),
+ key=lambda x: x.priority))
+
def getitem(self, obj, argument):
"""Get an item or attribute of an object but prefer the item."""
try:
@@ -407,15 +412,15 @@ def preprocess(self, source, name=None, filename=None):
because there you usually only want the actual source tokenized.
"""
return reduce(lambda s, e: e.preprocess(s, name, filename),
- self.extensions.itervalues(), unicode(source))
+ self.iter_extensions(), unicode(source))
def _tokenize(self, source, name, filename=None, state=None):
"""Called by the parser to do the preprocessing and filtering
for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
"""
source = self.preprocess(source, name, filename)
stream = self.lexer.tokenize(source, name, filename, state)
- for ext in self.extensions.itervalues():
+ for ext in self.iter_extensions():
stream = ext.filter_stream(stream)
if not isinstance(stream, TokenStream):
stream = TokenStream(stream, name, filename)
View
@@ -57,6 +57,13 @@ class Extension(object):
#: if this extension parses this is the list of tags it's listening to.
tags = set()
+ #: the priority of that extension. This is especially useful for
+ #: extensions that preprocess values. A lower value means higher
+ #: priority.
+ #:
+ #: .. versionadded:: 2.4
+ priority = 100
+
def __init__(self, environment):
self.environment = environment
View
@@ -34,7 +34,7 @@ def __init__(self, environment, source, name=None, filename=None,
self.filename = filename
self.closed = False
self.extensions = {}
- for extension in environment.extensions.itervalues():
+ for extension in environment.iter_extensions():
for tag in extension.tags:
self.extensions[tag] = extension.parse
self._last_identifier = 0
View
@@ -204,6 +204,16 @@ def test_streamfilter_extension(self):
out = tmpl.render()
assert out == 'Foo BAR Baz'
+ def test_extension_ordering(self):
+ class T1(Extension):
+ priority = 1
+ class T2(Extension):
+ priority = 2
+ env = Environment(extensions=[T1, T2])
+ ext = list(env.iter_extensions())
+ assert ext[0].__class__ is T1
+ assert ext[1].__class__ is T2
+
class InternationalizationTestCase(JinjaTestCase):

0 comments on commit 5b3f4dc

Please sign in to comment.