[svn] again some jinja updates, some minor performance and doc improvements
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent b475cff · Browse files · 12 files·+236 added−95 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+236 added−95 removed
- tests:+60 added−7 removed
- other:+176 added−88 removed
Provenance
- Commit
9bcd411- Tree
94e0bff- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
b475cff
12 files changed+236 added−95 removed
modified:docs/src/builtins.txt+9 added
172 unmodified lines173 is checked.174 175 *new in Jinja 1.1*176 177+`rendertemplate`178 179+ Loads and renders a template with a copy of the current context. This works180+ in many situations like the ``{% include %}`` tag, just that it does not181+ include a template and merges it into the template structure but renders182+ it completely independent and returns the rendered data as string.183+184+ *new in Jinja 1.1*185+186+187 Global Constants188 ================189 190 Jinja provides some special variables which cannot be overridden in templates.22 unmodified linesmodified:docs/src/designerdoc.txt+67 added-60 removed
349 unmodified lines350 351 For information regarding the visibility of macros have a look at the352 `Scopes and Variable Behavior`_ section.353 354+Extended Macro Call355+===================356+357+*new in Jinja 1.1*358+359+Jinja 1.1 adds a new special tag that you can use to pass some evaluable360+template code to a macro. Here an example macro that uses the features of361+the ``{% call %}`` tag:362+363+.. sourcecode:: html+jinja364+365+ {% macro dialog title %}366+ <div class="dialog">367+ <h3>{{ title }}</h3>368+ <div class="text">369+ {{ caller() }}370+ </div>371+ </div>372+ {% endmacro %}373+374+Called the normal way `caller` will be undefined, but if you call it375+using the new `{% call %}` tag you can pass it some data:376+377+.. sourcecode:: html+jinja378+379+ {% call dialog('Hello World') %}380+ This is an example dialog381+ {% endcall %}382+383+Now the data wrapped will be inserted where you put the `caller` call.384+385+If you pass `caller()` some keyword arguments those are added to the386+namespace of the wrapped template data:387+388+.. sourcecode:: html+jinja389+390+ {% macro makelist items %}391+ <ul>392+ {%- for item in items %}393+ <li>{{ caller(item=item) }}</li>394+ {%- endfor %}395+ </ul>396+ {%- endmacro %}397+398+ {% call makelist([1, 2, 3, 4, 5, 6]) -%}399+ [[{{ item }}]]400+ {%- endcall %}401+402+This will then produce this output:403+404+.. sourcecode:: html405+406+ <ul>407+ <li>[[1]]</li>408+ <li>[[2]]</li>409+ <li>[[3]]</li>410+ <li>[[4]]</li>411+ <li>[[5]]</li>412+ <li>[[6]]</li>413+ </ul>414+415+416 Template Inclusion417 ==================418 419 You can load another template at a given position using ``{% include %}``.15 unmodified lines435 436 This is intended because it makes it possible to include macros from other437 templates.438 439+*new in Jinja 1.1* you can now render an included template to a string that is440+evaluated in an indepdendent environment by calling `rendertemplate`. See the441+documentation for this function in the `builtins`_ documentation.442+443 Filtering Blocks444 ================445 446 Sometimes it could be a good idea to filter a complete block of text. For60 unmodified lines507 {{ macro_('foo') }}508 {% endfor %}509 510 445-Bleeding Edge446-=============447-448-Here are some features documented that are new in the SVN version and might449-change.450-451-``{% call %}``:452-453- A new tag that allows to pass a macro a block with template data:454-455- .. sourcecode:: html+jinja456-457- {% macro dialog title %}458- <div class="dialog">459- <h3>{{ title }}</h3>460- <div class="text">461- {{ caller() }}462- </div>463- </div>464- {% endmacro %}465-466- Called the normal way `caller` will be undefined, but if you call it467- using the new `{% call %}` tag you can pass it some data:468-469- .. sourcecode:: html+jinja470-471- {% call dialog('Hello World') %}472- This is an example dialog473- {% endcall %}474-475- If you pass `caller()` some keyword arguments those are added to the476- namespace of the wrapped template data:477-478- .. sourcecode:: html+jinja479-480- {% macro makelist items %}481- <ul>482- {%- for item in items %}483- <li>{{ caller(item=item) }}</li>484- {%- endfor %}485- </ul>486- {%- endmacro %}487-488- {% call makelist([1, 2, 3, 4, 5, 6]) -%}489- [[{{ item }}]]490- {%- endcall %}491-492- This will then produce this output:493-494- .. sourcecode:: html495-496- <ul>497- <li>[[1]]</li>498- <li>[[2]]</li>499- <li>[[3]]</li>500- <li>[[4]]</li>501- <li>[[5]]</li>502- <li>[[6]]</li>503- </ul>504-511 .. _slicing chapter: http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice512 .. _Scopes and Variable Behavior: scopes.txt513+.. _builtins: builtins.txtmodified:docs/src/filters.txt+12 added
55 unmodified lines56 57 If you're using Jinja with django and want to use the django filters in Jinja58 have a look at the `developer recipies`_ page.59 60+*new in Jinja 1.1* additionally to the `stringfilter` decorator there is now61+a similar decorator that works exactly the same but does not convert values62+to unicode:63+64+.. sourcecode:: python65+66+ from jinja.filters import simplefilter67+68+ @simplefilter69+ def do_add(value, to_add):70+ return value + to_add71+72 .. _designer documentation: builtins.txt73 .. _developer recipies: devrecipies.txtmodified:jinja/translators/python.py+6 added-6 removed
222 unmodified lines223 224 #: mapping of unsupported syntax elements.225 #: the value represents the feature name that appears226 #: in the exception.227- self.unsupported = {228- ast.ListComp: 'list comprehensions'229- }227+ self.unsupported = {ast.ListComp: 'list comprehension'}228 229 #: because of python2.3 compatibility add generator230 #: expressions only to the list of unused features231 #: if it exists.232 if hasattr(ast, 'GenExpr'):235- self.unsupported.update({236- ast.GenExpr: 'generator expressions'237- })233+ self.unsupported[ast.GenExpr] = 'generator expression'234 235+ #: if expressions are unsupported too (so far)236+ if hasattr(ast, 'IfExp'):237+ self.unsupported[ast.IfExp] = 'inline if expression'238+239 # -- public methods240 241 def process(environment, node):242 """973 unmodified linesmodified:jinja/environment.py+12 added-8 removed
20 unmodified lines21 22 __all__ = ['Environment']23 24 25+#: minor speedup26+_getattr = getattr27+28+29 class Environment(object):30 """31 The Jinja environment.32 263 unmodified lines296 return get_attribute(obj, name)297 except (AttributeError, SecurityException):298 pass299 if obj is self.undefined_singleton:296- return getattr(self.undefined_singleton, name)300+ return _getattr(obj, name)301 return self.undefined_singleton302 303 def get_attributes(self, obj, attributes):304 """13 unmodified lines318 if dyn_args is not None:319 args += tuple(dyn_args)320 if dyn_kwargs is not None:321 kwargs.update(dyn_kwargs)318- if getattr(f, 'jinja_unsafe_call', False) or \319- getattr(f, 'alters_data', False):322+ if _getattr(f, 'jinja_unsafe_call', False) or \323+ _getattr(f, 'alters_data', False):324 return self.undefined_singleton321- if getattr(f, 'jinja_context_callable', False):325+ if _getattr(f, 'jinja_context_callable', False):326 args = (self, context) + args327 return f(*args, **kwargs)328 329 def call_function_simple(self, f, context):330 """331 Function call without arguments. Because of the smaller signature and332 fewer logic here we have a bit of redundant code.333 """330- if getattr(f, 'jinja_unsafe_call', False) or \331- getattr(f, 'alters_data', False):334+ if _getattr(f, 'jinja_unsafe_call', False) or \335+ _getattr(f, 'alters_data', False):336 return self.undefined_singleton333- if getattr(f, 'jinja_context_callable', False):337+ if _getattr(f, 'jinja_context_callable', False):338 return f(self, context)339 return f()340 341 def finish_var(self, value, ctx):5 unmodified lines347 if value is None:348 return u''349 elif value is self.undefined_singleton:350 return unicode(value)347- elif getattr(value, 'jinja_no_finalization', False):351+ elif _getattr(value, 'jinja_no_finalization', False):352 return value353 val = self.to_unicode(value)354 if self.default_filters:355 val = self.apply_filters(val, ctx, self.default_filters)1 unmodified linemodified:jinja/filters.py+40 added-5 removed
9 unmodified lines10 """11 import re12 from random import choice13 from urllib import urlencode, quote14-from jinja.utils import urlize, escape, reversed14+from jinja.utils import urlize, escape, reversed, sorted15 from jinja.datastructure import TemplateData16 from jinja.exceptions import FilterArgumentError17 18 19+_striptags_re = re.compile(r'(<!--.*?-->|<[^>]+>)')20+21+22 def stringfilter(f):23 """24 Decorator for filters that just work on unicode objects.25 """12 unmodified lines38 pass39 return decorator40 41 42+def simplefilter(f):43+ """44+ Decorator for simplifying filters. Filter arguments are passed45+ to the decorated function without environment and context. The46+ source value is the first argument. (like stringfilter but47+ without unicode conversion)48+ """49+ def decorator(*args):50+ def wrapped(env, context, value):51+ return f(value, *args)52+ return wrapped53+ try:54+ decorator.__doc__ = f.__doc__55+ decorator.__name__ = f.__name__56+ except:57+ pass58+ return decorator59+60+61 def do_replace(s, old, new, count=None):62 """63 Return a copy of the value with all occurrences of a substring64 replaced with a new one. The first argument is the substring84 unmodified lines149 <ul class="my_list" id="list-42">150 ...151 </ul>152 131- As you can see it automatically appends a space in front of the item153+ As you can see it automatically prepends a space in front of the item154 if the filter returned something. You can disable this by passing155 `false` as only argument to the filter.156 157 *New in Jinja 1.1*531 unmodified lines689 return value690 return wrapped691 692 671-def do_striptags(value, rex=re.compile(r'<[^>]+>')):693+def do_striptags(value):694 """695 Strip SGML/XML tags and replace adjacent whitespace by one space.696 697 *new in Jinja 1.1*698 """677- return ' '.join(rex.sub('', value).split())699+ return ' '.join(_striptags_re.sub('', value).split())700 do_striptags = stringfilter(do_striptags)701 702 703 def do_slice(slices, fill_with=None):135 unmodified lines839 return func(value)840 return wrapped841 842 843+def do_sort(reverse=False):844+ """845+ Sort a sequence. Per default it sorts ascending, if you pass it846+ `True` as first argument it will reverse the sorting.847+848+ *new in Jinja 1.1*849+ """850+ def wrapped(env, context, value):851+ return sorted(value, reverse=reverse)852+ return wrapped853+854+855 FILTERS = {856 'replace': do_replace,857 'upper': do_upper,858 'lower': do_lower,37 unmodified lines896 'slice': do_slice,897 'batch': do_batch,898 'sum': do_sum,899 'abs': do_abs,866- 'round': do_round900+ 'round': do_round,901+ 'sort': do_sort902 }modified:jinja/utils.py+24 added-8 removed
37 unmodified lines38 return list.pop(self, 0)39 def clear(self):40 del self[:]41 42-# support for a working reversed()42+# support for a working reversed() in 2.343 try:44 reversed = reversed45 except NameError:46 def reversed(iterable):3 unmodified lines50 return iter(iterable[::-1])51 except TypeError:52 return iter(tuple(iterable)[::-1])53 54-# support for python 2.3/2.454+# set support for python 2.355 try:56 set = set57 except NameError:58 from sets import Set as set59 60+# sorted support (just a simplified version)61+try:62+ sorted = sorted63+except NameError:64+ def sorted(seq, reverse=False):65+ rv = list(seq)66+ rv.sort(reverse=reverse)67+ return rv68+69+#: function types70+callable_types = (FunctionType, MethodType)71+72+73 #: number of maximal range items74 MAX_RANGE = 100000075 76 _word_split_re = re.compile(r'(\s+)')76 unmodified lines153 _from_string_env = Environment()154 return _from_string_env.from_string(source)155 156 157+#: minor speedup158+_getattr = getattr159+160 def get_attribute(obj, name):161 """162 Return the attribute from name. Raise either `AttributeError`163 or `SecurityException` if something goes wrong.164 """165 if not isinstance(name, basestring):166 raise AttributeError(name)151- if name[:2] == name[-2:] == '__' or name[:2] == '::':167+ if name[:2] == name[-2:] == '__':168 raise SecurityException('not allowed to access internal attributes')153- if (obj.__class__ is FunctionType and name.startswith('func_') or154- obj.__class__ is MethodType and name.startswith('im_')):169+ if obj.__class__ in callable_types and name.startswith('func_') or \170+ name.startswith('im_'):171 raise SecurityException('not allowed to access function attributes')156- r = getattr(obj, 'jinja_allowed_attributes', None)172+ r = _getattr(obj, 'jinja_allowed_attributes', None)173 if r is not None and name not in r:158- raise SecurityException('not allowed attribute accessed')159- return getattr(obj, name)174+ raise SecurityException('disallowed attribute accessed')175+ return _getattr(obj, name)176 177 178 def safe_range(start, stop=None, step=None):179 """520 unmodified linesmodified:tests/test_filters.py+9 added-1 removed
59 unmodified lines60 ROUND = '''{{ 2.7|round }}|{{ 2.1|round }}|\61 {{ 2.1234|round(2, 'floor') }}|{{ 2.1|round(0, 'ceil') }}'''62 XMLATTR = '''{{ {'foo': 42, 'bar': 23, 'fish': none,63 'spam': missing, 'blub:blub': '<?>'}|xmlattr }}'''64+SORT = '''{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}'''65 66 67+68 def test_capitalize(env):69 tmpl = env.from_string(CAPITALIZE)70 assert tmpl.render() == 'Foo bar'71 43 unmodified lines115 116 def test_striptags(env):117 tmpl = env.from_string(STRIPTAGS)118 out = tmpl.render(foo=' <p>just a small \n <a href="#">'117- 'example</a> link</p>\n<p>to a webpage</p>')119+ 'example</a> link</p>\n<p>to a webpage</p> '120+ '<!-- <p>and some commented stuff</p> -->')121 assert out == 'just a small example link to a webpage'122 123 124 def test_filesizeformat(env):151 unmodified lines276 assert len(out) == 3277 assert 'foo="42"' in out278 assert 'bar="23"' in out279 assert 'blub:blub="<?>"' in out280+281+282+def test_sort(env):283+ tmpl = env.from_string(SORT)284+ assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'modified:tests/test_forloop.py+6 added
16 unmodified lines17 CYCLING = '''{% for item in seq %}{% cycle '<1>', '<2>' %}{% endfor %}\18 {% for item in seq %}{% cycle through %}{% endfor %}'''19 SCOPE = '''{% for item in seq %}{% endfor %}{{ item }}'''20 VARLEN = '''{% for item in iter %}{{ item }}{% endfor %}'''21+NONITER = '''{% for item in none %}...{% endfor %}'''22 23 24 def test_simple(env):25 tmpl = env.from_string(SIMPLE)47 unmodified lines73 yield item74 tmpl = env.from_string(VARLEN)75 output = tmpl.render(iter=inner())76 assert output == '01234'77+78+79+def test_noniter(env):80+ tmpl = env.from_string(NONITER)81+ assert not tmpl.render()modified:tests/test_macros.py+31 added
37 unmodified lines38 {% macro test %}{{ varargs|join('|') }}{% endmacro %}\39 {{ test(1, 2, 3) }}\40 '''41 42+SIMPLECALL = '''\43+{% macro test %}[[{{ caller() }}]]{% endmacro %}\44+{% call test() %}data{% endcall %}\45+'''46 47+COMPLEXCALL = '''\48+{% macro test %}[[{{ caller(data='data') }}]]{% endmacro %}\49+{% call test() %}{{ data }}{% endcall %}\50+'''51+52+CALLERUNDEFINED = '''\53+{% set caller = 42 %}\54+{% macro test() %}{{ caller is not defined }}{% endmacro %}\55+{{ test() }}\56+'''57+58+59 def test_simple(env):60 tmpl = env.from_string(SIMPLE)61 assert tmpl.render() == 'Hello Peter!'62 26 unmodified lines89 90 def test_varargs(env):91 tmpl = env.from_string(VARARGS)92 assert tmpl.render() == '1|2|3'93+94+95+def test_simple_call(env):96+ tmpl = env.from_string(SIMPLECALL)97+ assert tmpl.render() == '[[data]]'98+99+100+def test_complex_call(env):101+ tmpl = env.from_string(COMPLEXCALL)102+ assert tmpl.render() == '[[data]]'103+104+105+def test_caller_undefined(env):106+ tmpl = env.from_string(CALLERUNDEFINED)107+ assert tmpl.render() == 'True'modified:tests/test_various.py+14 added-6 removed
5 unmodified lines6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9 10-KEYWORDS = '''10+KEYWORDS = '''\11 {{ with }}12 {{ as }}13 {{ import }}14 {{ from }}11 unmodified lines26 {{ raise }}27 {{ yield }}28 {{ while }}29 {{ pass }}30-{{ finally }}31-'''32-30+{{ finally }}'''31 UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''34-32 RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''36-33 CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''34 35 36 def test_keywords(env):27 unmodified lines64 env = Environment()65 env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g66 tmpl = env.from_string(CALL)67 assert tmpl.render() == 'abdfh'68+69+70+def test_stringfilter(env):71+ from jinja.filters import stringfilter72+ f = stringfilter(lambda f, x: f + x)73+ assert f('42')(env, None, 23) == '2342'74+75+76+def test_simplefilter(env):77+ from jinja.filters import simplefilter78+ f = simplefilter(lambda f, x: f + x)79+ assert f(42)(env, None, 23) == 65modified:CHANGES+6 added-1 removed
53 unmodified lines54 - fixed a bug that allowed users to override the special names `_`, `true` etc.55 56 - added `batch` and `slice` filters for batching or slicing sequences57 58-- added `sum`, `abs` and `round` filters. This fixes #23858+- added `sum`, `abs`, `round` and `sort` filters. This fixes #23859 60 - added `striptags` and `xmlattr` filters for easier SGML/XML processing61 62 - the trans tag does not need explicit naming for variables with the same39 unmodified lines102 - It's now possible to iterate over iterators additionally to sequences.103 If the iterator is inifite it will crash however, so makes sure you don't104 pass something like that to a template!105 106+- added `rendetemplate` to render included templates in an isolated107+ environment and get the outout back.108 109+- added `simplefilter` decorator.110+111+112 Version 1.0113 -----------114 (released Mar 23, 2007)115 1 unmodified line